我有一張Products桌子。附有一張Attributes表格,具有一對多的關系,這意味著一個產品可以有許多不同的屬性。例如,我需要過濾請求以選擇所有原產地為中國的產品。我的要求,它適用于單一值。
Product::where('price','>',0)
->orderBy('price', "asc")
->with('attributes')
->whereHas('attributes', function(Builder $query){
$query->where('value_name', '=', 'China');
})->get();
我需要產品的位置China和Gray屬性一起
如果只有一個引數,那么它可以作業,但是可以有動態數量的引數,并且只需要選擇那些屬性將具有的產品,例如,中國的原產地和灰色。但是這個查詢回傳一個空的結果。
$products = Product::where('price', '>', 0)
->orderBy('price', "asc")
->with('attributes')
->whereHas('attributes', function(Builder $query){
$query->where('value_name','=' , 'China')
->where('value_name','=' , 'Grey');
})
->get();
part table Attributes bellow.
---- -------------------------------------- ---------------- -------------------------------------- ------------ ---------
| id | attribute_guid | attribute_name | value_guid | value_name | item_id |
---- -------------------------------------- ---------------- -------------------------------------- ------------ ---------
| 1 | 84c01488-bf53-11e9-80e3-00155dbf5a2a | Orign | e4a32025-24d2-11eb-bf54-00505600fc59 | China | 1 |
| 2 | 9790984e-1103-11ea-b773-b42e9983820e | Color | 8acbe31e-ddfa-11ea-bf53-00505600fc59 | Grey | 1 |
---- -------------------------------------- ---------------- -------------------------------------- ------------ ---------
uj5u.com熱心網友回復:
第二種where方法與 SQL 查詢中的 a 相同AND WHERE。您需要使用$query->where('value_name, 'China')->orWhere('value_name', 'Grey');或使用$query->whereIn('value_name', ['China', 'Grey']).
https://laravel.com/docs/9.x/queries#or-where-clauses - orWhere
https://laravel.com/docs/9.x/queries#additional-where-clauses - 附加where條款
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/492969.html
標籤:拉拉维尔
