在 eloquent 中:如何获得具有条件的相关模型的计数恰好为 n 的模型?

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

在 eloquent 中:如何关联一个模型,其中具有条件的相关模型的计数恰好是 n?

这里是我面临的问题的简单化:-

数据库中有多门课程。 一门课程有很多学生。

我需要正好有 20 名女学生参加课程。 所以,我需要两者都做。 检查学生人数是否为 20。 并检查他们是女性的条件。

现在我可以使用 "wherehas",这不会让我计算相关学生。实际上它只检查是否有至少一名女学生。

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

或者我可以使用 "has" 这让我可以计算相关学生但不会让我检查他们是否是女性。

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

我需要一些既能检查学生人数又能检查她们是否都是女性的东西。需要这样的东西:-

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

怎么办?

根据 Eloquent Relationships 文档,您可以这样做:

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