为什么laravel 6多对多关系无法正常工作?

时间:2020-03-02 12:18:15

标签: php laravel laravel-6

嗨,我只是想获得该角色的权限,我正在尝试关注

$r = Role::find(1);
dd($r->permissions);

上面的脚本没有返回任何权限,但是您可以看到下表中有数据。我也尝试跟随但没有运气

$role = Role::with('permissions')->where('id', 1)->first();

如您所见,表中有数据

表格: tes_permissions

enter image description here

表格: tes_roles

enter image description here

表格: tes_permission_role

enter image description here

以下是模型

class Permission extends Model
{

    protected $table = 'tes_permissions'

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

还有

class Role extends Model
{

    protected $table = 'tes_roles';

    public function permissions() {
        return $this->belongsToMany('App\Permission', 'tes_permission_role', 'permission_id', 'role_id');
    }
}

有人可以请我指导可能是什么问题,

1 个答案:

答案 0 :(得分:0)

您在belongsToMany()中混合了属性的顺序。第三个参数是为定义关系的模型指定ID。因此更改为以下内容:

public function permissions() {
    return $this->belongsToMany('App\Permission', 'tes_permission_role', 'role_id', 'permission_id');
}

Permission模型上,也要进行肯定定义。

public function roles()
{
    return $this->belongsToMany('App\Role', 'tes_permission_role', 'permission_id', 'role_id');
}