LoginSignup
14
12

More than 3 years have passed since last update.

Laravel EloquentのwhereHasメソッドが重いのでその代替案

Last updated at Posted at 2019-09-27

みなさんこんにちは tyamahoriです。
仕事でちょっとしたシステムをLaravelで作成する機会がありました。その中で注意しなければいけない点があったのでここに書き残したいともいます。

whereHasメソッドは重くて辛いょ。。

やっまりwhereHasメソッドを使うと重くて辛いんですよ。。ネットでググるとこんな感じで記事が出てきます

代替案ありました!

GitHubのissueを読み込んでみるとなんと解決策があるではないですか!!!
WhereHas query is too slow のコメント

Laravel is creating a temporary column on literally every row in the database, in which it fills with true or false. If any indexes can be used, they are probably used after this. Any query that uses whereHas is probably going to be a full table scan.

Here is a similar query, except it does not induce full table scans.

Profile::whereIn('profiles.id', function($query) use ($mac_address) {
    $query->from('devices')
        ->select('devices.profile_id')
        ->where('devices.mac_address', $mac_address);
})

なんとwhereInを使えばいいんですね。勉強になりました。issueに乗っているコードを必要に応じて読み替える必要はあります。実際、案件にてwhereHasとwhereInを比較してみたら、驚くくらいに挙動が軽くなりました!。whereHasを使っている方はぜひともwhereInを使ってみてくださいね!!

14
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12