我有一个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 |
+----+--------------------------------------+----------------+--------------------------------------+------------+---------+
第二个where
方法与SQL查询中的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
条款