Home > Net >  Laravel query builder for relation table whereHas and several values
Laravel query builder for relation table whereHas and several values

Time:06-20

I have a Products table. An Attributes table is attached to it, with one to many relation, this means that a product can have many different attributes. I need to filter the request in order to select, for example, all products whose origin is China. My request, it works with single value.

        Product::where('price','>',0)
                 ->orderBy('price', "asc")
                 ->with('attributes')
                 ->whereHas('attributes', function(Builder $query){
                  
                     $query->where('value_name', '=', 'China');
                     
                  })->get();

I need where the products have China and Gray attributes together
If there is only one parameter, then it works, but there can be a dynamic number of parameters and it is necessary to select only those products whose attributes will have, for example, the origin of China and the color Gray. But this query returns an empty result.

     $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 |
 ---- -------------------------------------- ---------------- -------------------------------------- ------------ --------- 

CodePudding user response:

The second where method is the same as a AND WHERE on an SQL query. You'll need to use the $query->where('value_name, 'China')->orWhere('value_name', 'Grey'); or use the $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 - additional where clauses

  • Related