Raj*_*shi 2 php mysql query-optimization laravel laravel-5
我正在使用此查询过滤出包含城市和类别的商店.当我在stores表中有大约1000条记录时,它工作正常.现在,当我有5000条记录时,生成结果大约需要3-10秒.
在我的案例中,商店属于多个类别.
如何使用Eloquent 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);
Run Code Online (Sandbox Code Playgroud)
使用whereRawas DB::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);
Run Code Online (Sandbox Code Playgroud)
解:
执行时间: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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1027 次 |
| 最近记录: |