【问题标题】:Laravel Eloquent - Retrieve data from relationshipLaravel Eloquent - 从关系中检索数据
【发布时间】:2019-12-11 09:50:42
【问题描述】:

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

数据库:

用户

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_permissions

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

}

Permission.php

class Permission extends Model {

protected $fillable = ['endpoint'];

protected $hidden = [];

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

}

请帮忙!

【问题讨论】:

  • 您在User 模型role() 中有错字。应该是App\UserRole
  • 谢谢泽山指出我的错别字????

标签: mysql laravel eloquent model


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2013-09-28
    • 2023-02-07
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多