Eloquent 地说:如何关联一个模型,其中具有条件的相关模型的数量恰好为 n?
这是我面临的问题的过度简化:-
数据库中有多个类(class)。 一门类(class)有很多学生。
我需要选修 20 名女学生的类(class)。 所以,我需要两者都做。 检查学生人数是否为 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()
关于laravel - Eloquent : How to get a model that has the count of a related model exactly n with a condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55051961/