【问题标题】:Is there any way to get product with his last price in laravel有没有办法以他在 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);
}

我收到了所有产品的所有价格,我不想要这个。

【问题讨论】:

    标签: php laravel api laravel-5 eloquent


    【解决方案1】:

    您可以向您的 Product 模型添加另一个关系,即:

    public function last_price()
    {
        return $this->hasOne('App\Product_price')->latest();
    }
    

    然后您可以急切地加载last_price 与您的$products,即:

    $products = Product::with('last_price')->get();
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2019-12-13
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多