【问题标题】:Laravel - Eloquent way to connect three tables using two pivotsLaravel - 使用两个枢轴连接三个表的雄辩方式
【发布时间】:2020-05-13 12:55:14
【问题描述】:

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');
    }
}

【问题讨论】:

  • 您要获取的数据样本
  • 我想获取用户字段以及角色和权限字段。
  • 你不能通过 User::with('roles', 'permission')->find(id); ?
  • @Qonvex620 出现错误Call to undefined relationship [permissions] on model [App\Admin\Admin].
  • 如果你想访问用户的权限,你可以使用 hasManyThrough 在你的用户模型中创建一个有权限的关系

标签: php laravel join pivot


【解决方案1】:

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

所以在这里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');
    }

    ...
}

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 2019-07-24
    • 2018-05-19
    • 2018-05-08
    • 2018-06-30
    • 2018-04-22
    • 1970-01-01
    • 2017-05-24
    • 2018-01-10
    相关资源
    最近更新 更多