我在Laravel 5.5中发表了很多关于多对多关系的错误
Illuminate \ Database \ QueryException(42000) SQLSTATE [42000]:语法错误或访问冲突:1066不唯一的表/别名:'用户' (SQL:选择
users
。*,users
。roles_id
为pivot_roles_id
,users
。users_id
为pivot_users_id
,{{ 1}}。users
为id
,pivot_id
。users
为created
,pivot_created
。users
为{{1} }updated
。pivot_updated
users
来自deleted
pivot_deleted
users
users
users
。id
=users
。users_id
其中users
。roles_id
= 2)
我有一个用户表,角色表和一个user_role表(数据透视表)。 user_role表包含以下列:id,users_id(来自users表的fk),roles_id(来自角色表的fk),创建,更新,删除。
在用户模型中我有
public function roles(){
return $this->belongsToMany(\App\roles::class,'roles','users_id','roles_id','id','id')->withPivot(['id','created','updated','deleted']);
}
在角色模型中我有
public function users(){
return $this->belongsToMany(\App\User::class,'users','roles_id','users_id','id','id')->withPivot(['id','created','updated','deleted']);
}
在我的控制器中我有
$roles = $this->rolesObject->whereNull('deleted')->orderBy('role')->get();
//Just for testing how to view the relationship won't be real code in the end
foreach($roles as $role){
foreach($role->users as $user){
dump($user->display_name);
}
}
查看文档,看起来我正在建立正确的关系,但显然我没有,我不知道我做错了什么
答案 0 :(得分:1)
belongsToMany
方法的第二个参数是关系表名称(docs),您必须传递role_user
而不是users
。
public function roles(){
return $this->belongsToMany(\App\roles::class,'role_user','users_id','roles_id','id','id')->withPivot(['id','created','updated','deleted']);
}
...
public function users(){
return $this->belongsToMany(\App\User::class,'role_user','roles_id','users_id','id','id')->withPivot(['id','created','updated','deleted']);
}
您的代码认为您的第二个参数users
是关系表名称,这就是错误的原因。