mysql - Laravel Eloquent - 从关系中检索数据

标签 mysql laravel eloquent model

我需要帮助才能从数据库中的用户、角色和权限之间的关系获取数据。请看下面...

数据库:

用户

id    name   role_id
1     Phil   1
2     Rob    1
3     Dave   2

用户角色

id    name
1     Admin
2     Staff

权限

id    endpoint
1     /users
2     /roles

用户角色权限

user_role_id     permissions_id
1                1
1                2
1                2

从用户模型中,我希望能够从权限表中获取数据,这样我就知道用户拥有什么访问权限。

这是模型:

用户.php

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable, SoftDeletes;

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

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = [
    'password',
];

protected $dates = [
    'deleted_at'
];

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

public permissions()
{
    ?????
}

}

用户角色.php

class UserRole extends Model {

protected $fillable = ['name'];

protected $hidden = [];

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

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

}

权限.php

class Permission extends Model {

protected $fillable = ['endpoint'];

protected $hidden = [];

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

}

请帮忙!

最佳答案

您已正确定义了所有必需的关系。您可以像这样使用它:

User::with('role.permissions')->first();
// It gives you all the permissions that are assigned to the role assigned to the underlying user :)
// Pretty vague to explain though

您不需要在 User 模型上定义 permission()

关于mysql - Laravel Eloquent - 从关系中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332046/

相关文章:

mysql - 选择时插入查询

mysql - 将数据从表 1 中的第 1 列复制到表 2 中的第 2 列并忽略重复项

javascript - 如何使用 Javascript 制作 Laravel 密码哈希

带有关系单元测试的 Laravel 用户层次结构出错了

php - 是否可以在 Laravel 中获取数据透视表与另一个表的关系?

php - 在mysql codeigniter中的一个查询中插入和更新

mysql - 使用 MongoDb 的数据库结构

laravel - 在我的 CentOS 中无法连接到我的 laravel 站点

php - 如何将上传的文件以给定的名称存储在磁盘上?

mysql - 通过 Laravel 迁移创建/使用存储过程