search
LoginSignup
0

posted at

【Laravel】whereHasとwithの違い

環境

Laravel v9.5.1 (PHP v8.1.3)

with

eager loadでN+1問題が解消される。

$users = User::with('post')->get();

foreach ($users as $user) {
    echo $user->posts;
}
select * from users
select * from posts where id in (1, 2, 3, 4, 5, …)

whereHas

リレーション先の条件でフィルタリングした結果を取得。

use Illuminate\Database\Eloquent\Builder;

$users = User::whereHas('posts', function (Builder $query) {
    $query->where('users.organization_id', $user->organization_id);
})->get();
select * from `posts` where exists (select * from `users` where `posts`.`user_id` = `users`.`id` and `users`.`organization_id` = ?)

参考

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
What you can do with signing up
0