【问题标题】:Laravel belongsToMany relation conditionLaravel belongsToMany 关系条件
【发布时间】:2019-07-08 12:58:21
【问题描述】:

我使用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();

但它不起作用。任何想法应该如何?感谢您的帮助。

【问题讨论】:

    标签: php mysql laravel eloquent relationship


    【解决方案1】:

    您可以为此添加whereHas 条件。试试下面的代码:

    $doctors = Doctor::with('categories')->whereHas('categories', function($query) {
            $query->where('id', 1);
        })->get();
    

    【讨论】:

      【解决方案2】:

      with() 函数实际上并没有在您的查询中引入连接,它只是将所有模型的关系加载为第二个查询。所以with() 函数不可能改变原来的结果集。

      您正在寻找的是whereHas()。这将在现有查询中添加一个WHERE EXISTS 子句。

      $doctors = Doctor::with('categories')->whereHas('categories', function ($query) {
          $query->where('categories.id', 1);
      })->get();
      

      【讨论】:

        【解决方案3】:

        使用->with() 实际上并不限制Doctor::...->get() 查询的结果;它只是告诉 Laravel 在 relationships 属性中返回什么。如果你真的想强制只返回具有第 1 类关系的医生,你需要使用whereHas()

        $doctors = Doctor::whereHas('categories', function($query) {
          $query->where('categories.id', '=', 1); 
          // `id` or `categories.id` should work, but `categories.id` is less ambigious
        })->get();
        

        【讨论】:

          猜你喜欢
          • 2016-07-13
          • 2020-02-28
          • 2015-02-22
          • 2018-05-19
          • 2018-03-08
          • 2021-03-22
          • 2021-10-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多