Search code examples
laravelcounteloquentone-to-manywherehas

In eloquent : How to get a model that has the count of a related model exactly n with a condition?


In eloquent : How to get related a model where count of related models with a condition is is exactly n?

Here is over simplification of the problem that I am facing:-

There are multiple courses in database. One course has many students.

I need to get courses with exactly 20 female students. So, I need to do both. Check that count of number of students is 20. And check the condition that they are female.

Now I can either use "wherehas" which does not let me count related students. In fact it only checks if there is at least one female student.

Course
    ::whereHas('students',function($q){
        $q->where('gender','Female');
    })
    ->get()
;

Or I can use "has" which lets me count the related students but does not let me check if they are female or not.

Course
    ::has('students','=','20')
    ->get()
;

I need something that allows me to do both checking the count of students and checking that they are all female. Something like this is needed:-

// NOT ALLOWED IN ELOQUENT
Course
    ::has('students','=','20',function($q){
        $q->where('gender','Female');
    })
    ->get()
;

What to do?


Solution

  • Per the Eloquent Relationships Documentation you can do something like this:

    Course
        ::whereHas('students',function($q){
            $q->where('gender','Female');
        }, '=', 20)
        ->get()