Laravel 5.3 Constraining Eager Loads not working

谁说我不能喝 提交于 2019-12-12 14:00:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!