環境
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` = ?)
参考