我正在嘗試以他的最后價格購買產品(價格與最后價格created_at)我有 :product 桌子:id, name,created_at, updated_atproduct_prices 桌子:id, product_id, price, created_at, updated_at在Product模型中:public function prices(){ return $this->hasMany('App\Product_price' , 'product_id', 'id');}在Product_price模型中:public function product(){ return $this->belongsTo('App\Product' , 'product_id');}上ProductController.php:public function GetALlProducts(){ $products = new Product; $products = $products->with('prices'); $products = $products->get(); return response()->json($products);}我收到了所有產品的所有價格,但我不想要這個。
1 回答

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
您可以向Product模型添加另一個關系,即:
public function last_price()
{
return $this->hasOne('App\Product_price')->latest();
}
然后你可以貪婪加載的last_price與您的$products,即:
$products = Product::with('last_price')->get();
- 1 回答
- 0 關注
- 156 瀏覽
添加回答
舉報
0/150
提交
取消