如何为每个用户从另一个表中获取具有角色的用户数组?有表users(id、name、email、email_verified_at、password、remember_token、created_at、updated_at)和roles(id、name、created_at、updated_at)。有必要在 UI 上显示用户及其角色的数据透视表。
还有一个链接表role_user:
[ id | user_id | role_id ]
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\User', 'role_user', 'role_id', 'user_id');
}
}
class User extends Authenticatable
{
...
public function roles()
{
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
}

老实说,这个问题措辞不佳。如果您需要显示 user_id、role_id 则只需输出您的链接表。没有显示用户、角色表中有哪些字段。如果一个
显示字段,那么制作两个具有相同值的表有什么意义。如果表格看起来像
然后只需通过 role_id 使用 join