如何用关系查询Laravel中的WhereAnd?
How to query WhereAnd in Laravel with relationships?
我有一个名为 Tutor
的模型,它有很多 Subjects
hasMany() relationship
。
我想编写一个查询来检索所有拥有物理和数学科目的导师。
Subjects的table结构如下:
id | title | tutor_id
实现它的最佳方法是什么?
$tutors = Tutor::whereHas('subjects', function($q) {
$q->where('title', 'physics')
->orWhere('title', 'maths');
})->get();
我不确定这个确切的代码是否有效,但你明白了。
解释一下,subjects
是Tutor
和Subject
的关系,title
应该是subject
table中的字段名。
要获得所有拥有 subjects
物理和数学的导师,您可以将查询写为:
Tutor::whereHas('subjects', function($q) {
$q->where('title', 'physics')
})
->whereHas('subjects', function($q) {
$q->where('title', 'maths')
})
->get();
我有一个名为 Tutor
的模型,它有很多 Subjects
hasMany() relationship
。
我想编写一个查询来检索所有拥有物理和数学科目的导师。
Subjects的table结构如下:
id | title | tutor_id
实现它的最佳方法是什么?
$tutors = Tutor::whereHas('subjects', function($q) {
$q->where('title', 'physics')
->orWhere('title', 'maths');
})->get();
我不确定这个确切的代码是否有效,但你明白了。
解释一下,subjects
是Tutor
和Subject
的关系,title
应该是subject
table中的字段名。
要获得所有拥有 subjects
物理和数学的导师,您可以将查询写为:
Tutor::whereHas('subjects', function($q) {
$q->where('title', 'physics')
})
->whereHas('subjects', function($q) {
$q->where('title', 'maths')
})
->get();