有没有办法以他在 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 - 获得没有外键的关系

在 laravel 中获得总预订量为零的天数

选择 EAV 方案中价格的所有产品

在 WooCommerce 中最后对特定产品类别的购物车项目进行排序

我的模型Laravel如何能够在hasMany中返回每个项目的所有价格?