【问题标题】:Laravel belongsToMany not returning resultsLaravel belongsToMany 不返回结果
【发布时间】:2017-01-28 12:36:06
【问题描述】:

我设置了以下架构:

用户:

  • 身份证

部门:

  • 身份证

部门用户:

  • 身份证
  • department_id
  • user_id

我还建立了以下关系:

用户模型

public function departments()
{
    return $this->belongsToMany('App\Resources\Eloquent\Models\Department', 'department_users');
}

部门模型

public function users()
{
    return $this->belongsToMany(User::class, 'department_users');
}

由于某种原因,当我尝试通过用户模型 $user->departments 访问时,它不起作用 - 但 $department->users 可以。

输出雄辩的查询如下:

select `departments`.*, `department_users`.`user_id` as `pivot_user_id`, `department_users`.`department_id` as `pivot_department_id` from `departments` inner join `department_users` on `departments`.`id` = `department_users`.`department_id` where `department_users`.`user_id` is null

我似乎无法弄清楚它为什么要查看 department_users.user_id 是否为空,而它应该在寻找用户 ID 时。

有什么想法吗?

【问题讨论】:

  • 你是怎么想出$user 变量的?如果用户还没有被保存,我相信 id 会为空。
  • 为什么要定义 return $this->belongsToMany(User::class, 'department_users'); - 删除第二个参数“department_users”,在用户模型中也删除第二个参数。它的可选表名,我在此定义中看到拼写错误的“department_users”与顶部“department_user”的架构 - 缺少最后一个“s”
  • $user 变量已分配给已从数据库中提取的模型。即:$user = User::find(1)
  • 表示关系函数中的外键和主键。可能这些会对你有所帮助。

标签: php mysql laravel eloquent models


【解决方案1】:

出于某种原因,如果我将关系设为以下 - 它会起作用。

 return $this->belongsToMany(Department::class, 'department_users')->orWhere('department_users.user_id', $this->id);

如果有人知道原因,请告诉我

【讨论】:

    【解决方案2】:

    为什么不按照文档here 中的建议设置模型:

    所以你的模型看起来像这样:

    用户模型

    public function departments()
    {
        return $this->belongsToMany('path\to\your\model\Department');
    }
    

    部门模型

    public function users()
    {
        return $this->belongsToMany(path\to\your\model\User);
    }
    

    Eloquent 将按字母顺序连接两个相关的模型名称。因此在定义关系时不需要额外的参数,并且 Laravel 默认情况下也会使模型键出现在枢轴对象上。然后你可以这样做:

    $department = path\to\your\model\Department::find(1);
    
    foreach ($department->users as $user) {
        echo $user;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2018-10-21
      • 2015-10-01
      • 1970-01-01
      • 2019-08-30
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多