且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用户和角色关系在laravel 5?

更新时间:2023-02-25 23:08:12

我遇到问题,我在用户表中有一个角色列,所以当我在做

  $ user-> role-> role_name 
/ pre>

它正在获取角色列而不是关系。


I have two tables :

User ->
 id : 
 name : 
 role_id : ->refernces('id')->on('roles');

Roles ->
 id :
 role_name :
 access :

I am trying to access roles details from user.

My user model has :

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

My role model has :

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

        ];

I get error :

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. How to do that?

I got the problem, i was having a role column in user table, so when i was doing

$user->role->role_name

it was fetching role column instead of relationship.