LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】whereHasとwithの違い

Posted at

環境

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` = ?)

参考

0
0
0

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
0
0