->where(function($query) {
return $query->where( property_id ) // 4
->where( property_value_id ); // 1
})
->where(function($query) {
return $query->where( property_id ) // 7
->where( property_value_id ); // 6
})
->where(function($query) {
return $query->where( property_id ) // 6
->where( property_value_id ); // 3
})
Laravel Query Builder where
Hi, i cant find the right query for this:
Table Producst
ad_id| property_id | property_value_id
69 | 4 | 1
69 | 7 | 6
69 | 6 | 3
67 | 4 | 1
67 | 6 | 3
67 | 7 | 6
67 | 7 | 5
71 | 4 | 1
71 | 7 | 5
72 | 4 | 1
72 | 7 | 6
72 | 6| 3
...
I need to search (where property_id = 4 and property_value_id = 1) and (where property_id = 7 and property_value_id = 6) and (where property_id = 6 and property_value_id = 3) the result should be: 69, 67, 72
How would you do that in Laravel Query Builder ?
For that simpler table, it sounds like you want the following sql:
select ad_id
from products
where(property_id = 4 and property_value_id = 1)
OR (property_id = 7 and property_value_id = 6)
group by ad_id
having count(ad_id) = 2
You can't make it all and because there is no row that fulfils that requirement.
So what this does is find all the rows that have at least one of the requirements and group them by ad_id.
The having count(ad_id) is there to only select out those that have all the requirements. This equals 2 since you have two sets of row requirements that needs to be fulfilled. In your original query this would be 3.
If you then wanted to translate that to query builder:
DB::table('products')
->where(function ($query) {
$query->where('property_id', 4)
->where('property_value_id', 1);
})
->orWhere(function ($query) {
$query->where('property_id', 7)
->where('property_value_id', 6);
})
->select('ad_id')
->groupBy('ad_id')
->havingRaw('count(ad_id) = ?', [2]);
I haven't tested the query builder version but it should be right.
Please or to participate in this conversation.