Laravel 5中如何建立用户和角色关系 [英] How to make user, and roles relationship in Laravel 5
本文介绍了Laravel 5中如何建立用户和角色关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个表:
User ->
id :
name :
role_id : ->references('id')->on('roles');
Roles ->
id :
role_name :
access :
我正在尝试从用户访问角色详细信息.
I am trying to access roles details from user.
我的用户模型具有:
public function role()
{
return $this->belongsTo('App\Role');
}
我的榜样有:
public function user()
{
return $this->hasMany('App\User');
}
当我尝试执行以下操作时:
When I try to do following :
$user = User::find(1);
$details = [
'name' => $user->first_name,
'role' => $user->role->role_name
];
我收到错误消息:
试图获取非对象的属性
Trying to get property of non-object
我的角色表包含访问列,其中包含对不同路由的权限数组.因此,我的用户将只有一个角色.一个角色可以有多个用户.
My roles table contains access columns containing array of permissions to different routes. So my user will have only one role. While a role can have multiple users.
该怎么做?
推荐答案
我遇到了问题,我在用户表中有一个角色列,所以当我这样做时
I got the problem, i was having a role column in user table, so when i was doing
$user->role->role_name
它正在获取 role
列而不是关系.
it was fetching role
column instead of relationship.
这篇关于Laravel 5中如何建立用户和角色关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文