php - Laravel 属于ToMany 关系条件

标签 php mysql laravel eloquent relationship

我使用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/

相关文章:

php - 如何计算 while 循环中未选中的复选框

php - 如何显示 PDO 创建的查询的全文?

mysql - 根据另一列查询 mysql 中的 REGEX_REPLACE

mysql - 操作 'UNION' 的排序规则组合非法

php - symfony用较低的函数创建数据库索引

php - 我应该使用 EAV 模型吗?

mysql - Navicat Premium Essentials 不支持 SSH

laravel - 在 Laravel 4 中加载 p12 文件

php - Laravel:为什么在实例化其提供的类时不调用已注册的服务提供者?

php - 如何在 Laravel 的 MySQL 查询中的 where 子句中使用数组