gpt4 book ai didi

mysql - Laravel - 获取用户及其角色名称

转载 作者:行者123 更新时间:2023-11-29 04:36:56 24 4
gpt4 key购买 nike

我需要让我的用户在标准 Auth 系统上拥有他们的角色(列出,而不是检查!)。
我是这样想的:

$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''名字'
用户角色
'用户身份''角色_id'

最佳答案

试试这段代码

应用/用户

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

Controller

  use App/User;

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

}

关于mysql - Laravel - 获取用户及其角色名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com