Laravel Eloquent-从关系中检索数据

时间:2019-08-02 18:54:35

标签: mysql laravel eloquent model

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

数据库:

用户

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

user_roles

id    name
1     Admin
2     Staff

权限

id    endpoint
1     /users
2     /roles

user_role_permissions

user_role_id     permissions_id
1                1
1                2
1                2

从用户模型中,我希望能够从权限表中获取数据,因此我知道用户具有什么访问权限。

这是模型:

User.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()
{
    ?????
}

}

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

}

Permission.php

class Permission extends Model {

protected $fillable = ['endpoint'];

protected $hidden = [];

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

}

请帮助!

1 个答案:

答案 0 :(得分:0)

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

Child

您无需在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 模型上定义permission()

相关问题