我有一個名為 products 的表,每次用戶更新他們的產品時,都會在另一個名為 product_price_history 的表中保存一個新行。
我的桌子:
產品 :
id (primary key)
name (varchar)
price (decimal)
產品價格歷史:
id (primary key)
product_id (fk to products)
price (decimal)
created_at (dateTime)
我的模型:
產品
產品價格歷史
我在product model里面寫了child table的關系如下
class Product extends Model {
public function history()
{
return $this->hasMany(ProductPriceHistory::class, 'product_id', 'id');
}
}
如何在 Laravel 中撰寫查詢以顯示價格下降的產品串列?換句話說,顯示最近價格下降的產品串列。
$result = Product::whereHas('history' , function($query){
// I do not know what to write here ...
})->get();
uj5u.com熱心網友回復:
您創建的查詢是正確的,只需添加降序過濾器
查詢將是這樣的:
$result = Product::whereHas('history' , function($query){
$query->orderBy('price', 'DESC');
})->get();
uj5u.com熱心網友回復:
在模型中使用
protected $with = ['history'];
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418171.html
標籤:
