我使用belongsToMany
函数创建了多对多关系:
class Doctor extends Model
{
...
public function categories()
{
return $this->belongsToMany('App\Category', 'doctors_to_categories', 'doctor_id', 'category_id');
}
...
}
现在我想创建具有多对多条件的查询。在 SQL 中将是:
SELECT *
FROM `doctors`
JOIN `doctors_to_categories`
ON `doctors_to_categories`.`doctor_id` = `doctors`.`id`
WHERE `doctors_to_categories`.`category_id` = 1
我尝试过这样的实现:
$doctors = Doctor::with(['categories' => function($query) {
$query->where('category_id', '=', 1);
}])->get();
或者
$doctors = Doctor::with(['categories' => function($query) {
$query->where('categories.id', '=', 1);
}])->get();
但是它不起作用。有什么想法应该如何吗?感谢您的帮助。
最佳答案
with()
函数实际上并没有在查询中引入联接,它只是加载所有模型的关系作为第二个查询。因此 with()
函数不可能更改原始结果集。
您正在寻找的是whereHas()
。这将向现有查询添加一个 WHERE EXISTS
子句。
$doctors = Doctor::with('categories')->whereHas('categories', function ($query) {
$query->where('categories.id', 1);
})->get();
关于php - Laravel 属于ToMany 关系条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691430/