问题
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