php - Laravel 5 `belongsToMany` 与 `wherePivot` Eloquent 查询无法正常工作

标签 php mysql laravel laravel-5 eloquent

假设我有users,coursescourse_users 表,用户属于许多类(class),数据透视表course_users 的结构如下:

|用户 ID |类(class)编号 |关系类型 |
|-------------------------------------------- -|

现在我有波纹管代码:

$user = User:find(1);

我在 user 模型中有以下功能:

public function courses(){
    return $this->belongsToMany('App\Models\Course')->wherePivot('relation_type', 1)->orWherePivot('relation_type', 0)->withPivot('relation_type', 'created_at', 'updated_at');
}

如果我想获得用户的类(class):

$user->courses();

但是上述函数的输出查询是这样的:

select 
  `courses`.*, `course_user`.`user_id` as `pivot_user_id`,`course_user`.`course_id` as `pivot_course_id`, 
  `course_user`.`relation_type` as `pivot_relation_type`,`course_user`.`created_at` as `pivot_created_at`, `course_user`.`updated_at` as `pivot_updated_at` 
from 
  `courses` inner join `course_user` on `courses`.`id` = `course_user`.`course_id` 
where 
  `course_user`.`user_id` = '1' and `course_user`.`relation_type` = '0' or `course_user`.`relation_type` = '1';

但我需要这样的东西:

select 
   `courses`.*, `course_user`.`user_id` as `pivot_user_id`, `course_user`.`course_id` as `pivot_course_id`, 
   `course_user`.`relation_type` as `pivot_relation_type`, `course_user`.`created_at` as `pivot_created_at`, `course_user`.`updated_at` as `pivot_updated_at` 
from 
   `courses` inner join `course_user` on `courses`.`id` = `course_user`.`course_id` 
where 
   `course_user`.`user_id` = '1' and (`course_user`.`relation_type` = '0' or `course_user`.`relation_type` = '1');

区别在于 where 子句。

最佳答案

关系上的 wherePivot 方法只是 where 方法的快捷方式,但它负责为约束添加数据透视表限定符。因此,它不支持闭包,而闭包是您对约束进行分组所需要使用的。因此,您需要直接调用where 方法,并在您的where 条件中手动添加表名限定符。

类似于:

public function courses() {
    return $this->belongsToMany('App\Models\Course')
        // pass a closure to group your constraints
        ->where(function ($query) {
            return $query->where('course_user.relation_type', 1)
                ->orWhere('course_user.relation_type', 0);
        })
        ->withPivot('relation_type', 'created_at', 'updated_at');
}

关于php - Laravel 5 `belongsToMany` 与 `wherePivot` Eloquent 查询无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36003441/

相关文章:

php - 如何在 Symfony 2 中返回实体的本地化属性

php - 奇怪的问题日期在 php 中正确打印,但插入数据库为 -2017

mysql - 存储过程中的 if else 存在问题

php - 日期差异计算天数差异的奇怪 PHP 5.3 问题

php - 查询用于循环的数据库

php - 未获取数据

mysql - MongoDB vs MySQL 性能 - 简单查询

css - 在 Laravel 4 中加载响应式 CSS

mysql - Laravel group by 和 SUM

php - 如何在laravel Controller 的URL请求中添加自定义变量?