Laravel belongsToMany 未返回结果

Laravel belongsToMany not returning results

我设置了以下架构:

用户:

部门:

department_user:

我还建立了以下关系:

用户模型

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 可以。

输出eloquent查询如下:

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。

有什么想法吗?

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

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

用户模型

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

部门模型

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

Eloquent 将按字母顺序加入两个相关的模型名称 order.So 您在定义关系时不需要额外的参数,并且 Laravel 默认情况下也会显示模型键枢轴对象。然后你可以这样做:

$department = path\to\your\model\Department::find(1);

foreach ($department->users as $user) {
    echo $user;
}

出于某种原因,如果我建立以下关系 - 它有效。

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

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