-
Notifications
You must be signed in to change notification settings - Fork 11.5k
Description
Few days ago, some of our members complaint that in few pages website is very slow. After investigated the issue, i found that "those pages are using wherehas() and has()" for querying relationship. To see the performance of those queries, i have checked the run time of those queries using the following function:
dd(DB::getQueryLog());
Result is unpleasant. the query takes about 69 sec in my local environment and about 1 sec in the server.
My local Mac:
Processor 2.4 GHz Intel Core i7 - 4 cores
Memory 8 GB 1600 MHz DDR3
Server: hosted in a cloud with 8 cores CPU.
Relationship:
public function posts()
{
return $this->belongsToMany('Post')->withPivot('views')->withTimestamps();
}
$users = User::remember(5)
->has('posts')
->with('comments')
->orderBy('updated_at', 'DESC')
->take(25)
->get();
Output:
dd(DB::getQueryLog());
array (size=3)
'query' => string 'select * from `users` where `users`.`deleted_at` is null and (select count(*) from `posts` inner join `comments` on `posts`.`id` = `comments`.`post_id` where `posts`.`deleted_at` is null and `comments`.`user_id` = `users`.`id` and `posts`.`deleted_at` is null) >= ? order by `updated_at` desc limit 25' (length=333)
'bindings' =>
array (size=1)
0 => int 1
'time' => float 68973.13
note: for security reason, i have changed the table names. however, i concept is same.
First, I thought that this might be the server or PHP issue. However, when i have run the raw query to the database server using "Sequel Pro", the result is same.
select * from `users`
where `users`.`deleted_at` is null
and
(
select count(*) from `posts`
inner join `comments` on `posts`.`id` = `comments`.`post_id`
where `posts`.`deleted_at` is null
and `comments`.`user_id` = `users`.`id`
and `posts`.`deleted_at` is null
) >= 1
order by `updated_at` desc limit 25;
Time taken : 69.8 s (in my local pc)
Time taken: 945ms (in Server)