我有超过6万条记录,我使用Has()来获取关系记录,但是对于查询,它的分页速度超过5秒,而查询速度则为2秒。
$products = Item::has('product_save');
我的查询:
select * from `products` where exists (select * from `product_saves` where `products`.`id` = `product_saves`.`product_id` and `user_id` = 2)
我使用Item来做相同的条件并按where()过滤。就像产品仍然活跃或5至88之间没有价格...
有什么办法优化它?我在表中添加了一个索引,但仍然很慢。
我建议使用Laravel's database query builder而不是ORM,并在子查询中选择1而不是all(*)。试试这个:
DB::table('products')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('product_saves')
->whereRaw('products.id = product_saves.product_id AND user_id = 2');
})
->get();