【问题标题】:Laravel - Get users with their roles nameLaravel - 获取用户及其角色名称
【发布时间】:2016-12-26 15:49:38
【问题描述】:

我需要让我的用户在标准身份验证系统上获得他们的角色(列出,而不是检查!)。
我有这样的想法:

$users = DB::table('users')
            ->join( 'user_roles', 'users.id', '=', 'user_roles.user_id' )
            ->select('id', 'first_name', 'role_id')
            ->get();

我得到了这个:

array:2 [▼
  0 => {#552 ▼
    +"id": 9670
    +"first_name": "Paweł"
    +"role_id": 1337
  }
  1 => {#553 ▼
    +"id": 9670
    +"first_name": "Paweł"
    +"role_id": 100
  }
]

但我需要这个:

array:2 [▼
  0 => {#552 ▼
    +"id": 9670
    +"first_name": "Paweł"
    +"roles": 'Admin, AnotherRole'
  }
]

我该怎么做? 我的表的结构:
用户
'ID' '名' ...等
角色
'ID' “名称”
user_roles
'用户身份' 'role_id'

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    在您的用户类中添加:

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

    现在可以了

    $user->roles
    

    访问角色。

    文档:https://laravel.com/docs/5.2/eloquent-relationships#many-to-many

    【讨论】:

      【解决方案2】:

      试试这个代码

      应用/用户

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

      控制器

        use App/User;
      
        public funtion getUsers(User $user)  {
          $getUsersWithRole =  $user->with('roles')->get();
          dd($getUsersWithRole);
      
        }
      

      【讨论】:

        【解决方案3】:

        用户模型:

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

        控制器:

         use App/User;
        
          public funtion index(User $user)  {
            $users=  User::with('roles')->get();    
          }
        

        【讨论】:

          猜你喜欢
          • 2023-04-04
          • 2021-05-29
          • 2018-05-09
          • 2017-09-19
          • 2017-11-13
          • 2021-01-05
          • 1970-01-01
          • 1970-01-01
          • 2017-04-03
          相关资源
          最近更新 更多