我正在使用此查询来筛选出具有城市和类别的商店。当我在stores
表中有大约1000条记录时,它工作正常。现在,当我有5000条记录时,大约需要3到10秒才能生成结果。
在我的情况下,商店属于多个类别。
我该如何使用雄辩orm优化此查询DB::raw()
?
$stores = Store::where('city_id', $city_id)
->where('disabled', '0')
->whereHas('categories', function($q) use ($category_id){
$q->where('category_id', '=', $category_id);
})
->orderBy('rating','DESC')->paginate(10);
我使用whereRaw
asDB::raw()
或DB::select()
不能paginate()
使用集合解决了我的问题。
问题:
执行时间:11.449304103851s
city_id = 6
和 $category_id = 1
$stores = Store::where('city_id', $city_id)
->where('disabled', '0')
->whereHas('categories', function($q) use ($category_id){
$q->where('category_id', '=', $category_id);
})
->orderBy('rating','DESC')->paginate(10);
解决方案:
执行时间:0.033660888671875s
city_id = 6
和 $category_id = 1
$stores = Store::
where('city_id', $city_id)
->where('disabled', '0')
->whereRaw('stores.id in (select store_id from store_categories_pivot where category_id = ?)', [$category_id])
->orderBy('rating','DESC')
->paginate(10);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句