Well first of all. Indexes. Are you sure you indexing optimally for the queries being run? Make some benchmarks with dummy data or use explain to see how the query is performed
Query by relations and problem with whereHas speed
I have models Product, Property, PropertyValue and product_property_value intermediate table for Many to Many relation with structure: product_id property_id When products fiters are in action, filter generate query builder like this
Product::query()
->whereHas('propertyValues', function ($query) {
$query->where('property_id', 'some_property_id');
$query->whereIn('value', ['red', 'blue']);
})
->whereHas('propertyValues', function ($query) {
$query->where('property_id', 'some_property_id');
$query->whereBetween('value', [20, 1000]);
})
->whereHas('propertyValues', function ($query) {
$query->where('property_id', 'some_property_id');
$query->where( 'value', 'usa');
});
It works properly but query can takes up to 1-10 seconds when many different filters are selected. I think it happened because query like this generates many joins in table with thousands items. ( Every whereHas subquery generate one join ) like this:
... and exists (select * from `property_values` inner join `product_property_value` on `property_values`.`id` = `product_property_value`.`property_value_id` where `products`.`id` = `product_property_value`.`product_id` and `property_id` = ?...
I found similar problems and there are well explained in this video https://www.youtube.com/watch?v=JOnXX-N96NE So the question is - how can i solve this issue??? Because it is trivial task for e-commerce. Maybe there is some trick with query without whereHas? In video developer replace whereHas with select trick but in my case I need to search not only ids, but it may be whereIn and array or even range or something else... Any ideas ?
Please or to participate in this conversation.