问题
I have two model User
and Profile
in one to one relationship.
I want to retrieve all user where profile.status == TRUE
using following code.
$users = User::with(['profile' => function ($query) {
$query->where('status', TRUE);
}])->get();
dd(count($users)); //50
I have 50 users and only among of them only 3 has status == TRUE
. But always it display 50.
回答1:
You are getting 50 users because you are applying condition to profile
. dd($user->profile)
you will get only the records of the profile whose status is true.
Use whereHas()
:
$users = User::whereHas('profile', function ($query) {
$query->where('status', TRUE);
})->get();
dd(count($users));
回答2:
If you want to make it work with single Query, you can use Query Builder join
like
\DB::table('users')->join('profile', function ($join){
$join->on('users.id', '=', 'profile.user_id')->where('profile.status', '=',TRUE);
})->get();
回答3:
You said you're having N+1 problem, so you need to use both whereHas()
and with()
like this to get users with profiles and to solve N+1 problem:
$users = User::whereHas('profile', function ($query) {
$query->where('status', TRUE);
})
->with('profile')
->get();
来源:https://stackoverflow.com/questions/40797538/laravel-5-3-constraining-eager-loads-not-working