Laravel 5 eloquent with whereHas more than 3. How to?

我怕爱的太早我们不能终老 提交于 2019-12-25 17:04:10

问题


it seems that it does not work, when I'm using "with" and function inside it and later trying to use "has" function. Here's the code, it should be easier to understand:

$users = Users::where("active","=", "1")->with(['photos' => function($q){
            $q->where('type','!=', 2);
       }])->has('photos', '>', 3)->paginate(8);
}

It seems, that it should return user ONLY if he has 3 photos which are NOT of type 2. But it doesn't care about "where" clause and return it without checking to the type.

How can I achieve what I'm seeking?

Thank you!


回答1:


The constraint on the eager loading of photos will not affect the query to get the users at all. You need to use the whereHas() method to add your type constraint to the photos check.

The whereHas() method is just syntactic sugar for calling the has() method with a callback properly. The whereHas() method also accepts an operator and a count. Therefore, the following should work:

$users = Users::with(['photos' => function($query) {
        $query->where('type', '!=', 2);
    }])
    ->where("active","=", "1")
    ->whereHas('photos', function ($query) {
        $query->where('type', '!=', 2);
    }, '>', 3)
    ->paginate(8);


来源:https://stackoverflow.com/questions/36025233/laravel-5-eloquent-with-wherehas-more-than-3-how-to

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