如何在Laravel 5.5中实现这种多对多关系?

时间:2018-02-21 22:36:00

标签: php laravel many-to-many laravel-5.5 laravel-eloquent

我在Laravel 5.5中发表了很多关于多对多关系的错误

  

Illuminate \ Database \ QueryException(42000)   SQLSTATE [42000]:语法错误或访问冲突:1066不唯一的表/别名:'用户' (SQL:选择users。*,usersroles_idpivot_roles_idusersusers_idpivot_users_id,{{ 1}}。usersidpivot_iduserscreatedpivot_createdusers为{{1} } updatedpivot_updated users来自deleted pivot_deleted users users usersid = usersusers_id其中usersroles_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);
    }
}

查看文档,看起来我正在建立正确的关系,但显然我没有,我不知道我做错了什么

1 个答案:

答案 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是关系表名称,这就是错误的原因。