我有一张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 |
+----+--------------------------------------+----------------+--------------------------------------+------------+---------+发布于 2022-06-19 18:38:16
第二个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条款
https://stackoverflow.com/questions/72679405
复制相似问题