[英]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
可以。
输出雄辩的查询如下:
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
我似乎无法弄清楚为什么它应该在查找用户ID时才查看department_users.user_id
是否为null。
有任何想法吗?
你为什么不设置你的模型像它在文档中建议在这里 :
因此,您的模型将如下所示:
用户模型
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;
}
由于某种原因,如果我建立以下关系-它将起作用。
return $this->belongsToMany(Department::class, 'department_users')->orWhere('department_users.user_id', $this->id);
如果有人知道为什么,请告诉我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.