有没有办法以他在 laravel 的最后价格获得产品
Posted
技术标签:
【中文标题】有没有办法以他在 laravel 的最后价格获得产品【英文标题】:Is there any way to get product with his last price in laravel 【发布时间】:2020-01-05 18:45:50 【问题描述】:我正在尝试以他的最后一个价格(最后一个价格created_at
)获得产品
我有:
product
表:
id, name,created_at, updated_at
product_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】:您可以向您的 Product
模型添加另一个关系,即:
public function last_price()
return $this->hasOne('App\Product_price')->latest();
然后您可以急切地加载last_price
与您的$products
,即:
$products = Product::with('last_price')->get();
【讨论】:
以上是关于有没有办法以他在 laravel 的最后价格获得产品的主要内容,如果未能解决你的问题,请参考以下文章
有没有办法根据 laravel 中相同模型中的值获得不同的值以及行数?
Laravel - Eloquent - 获得没有外键的关系