繁体   English   中英

Laravel - 使用两个枢轴连接三个表的雄辩方式

[英]Laravel - Eloquent way to connect three tables using two pivots

Laravel 新手,

我有三个表usersrolespermissions 这些与以下两个数据透视表role_userpermission_role

在这里我想连接三个表,这样我就可以得到像多对多一对多关系这样的结果。 例如,我可以获得给定用户的所有权限和角色(一对多),反之亦然,以获得彼此的角色和权限。 另外,我想获取所有用户以及各自的角色和权限,反之亦然。

我刚刚在社区的帮助下解决了为给定用户获取角色的问题,但现在我坚持获得上述结果。 谁能帮我实现它?

数据库图

在此处输入图片说明

用户模型

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


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

好榜样

<?php

namespace App\Admin;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    protected $fillable = ['name', 'display'];

    public function permissions()
    {
        return $this->belongsToMany('App\Admin\Permission');
    }

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

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

}

权限模型

<?php

namespace App\Admin;

use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    protected $fillable = ['model', 'can'];

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

首先感谢@He提供了一个方向。

所以在这里with()我不得不添加roles模型来调用它的permissions方法。 所以代码将如下所示。

User::with('roles', 'roles.permissions')->find($id);

所以这里的roles.permissionsRole模型中的permissions()方法

好榜样

class Role extends Model
{
    protected $fillable = ['name', 'display'];

    public function permissions()
    {
        return $this->belongsToMany('App\Admin\Permission');
    }

    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM