[英]get array of roles ID of a User in laravel
這是用戶模型:
class User extends Model
{
/**
* The roles that belong to the user.
*/
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
這是角色模型:
class Role extends Model
{
/**
* The users that belong to the role.
*/
public function users()
{
return $this->belongsToMany('App\User');
}
}
如您所見,這兩個模型之間存在多對多關系。
現在我想獲取用戶角色ID 的數組。 為此,我寫了這個:
$user = User::find($id);
return $user->roles()->get(['roles.role_id']);
但上面的代碼返回一個數組,其中包含引用用戶擁有的每個角色 ID 的對象:
[
{
"role_id": 9,
"pivot": {
"user_id": 2,
"role_id": 9
}
},
{
"role_id": 14,
"pivot": {
"user_id": 2,
"role_id": 14
}
}
]
但我想返回一個角色 ID 數組,如下所示:
[9,14,......]
我怎樣才能做到這一點 ?
lists()
雄辯的函數對此很有幫助。 請注意,它返回一個集合,而不是數組,因此,如果必須具有該數組,則還需要toArray
。
$roles = $user
->roles()
->lists('roles.role.id')
->toArray();
更新 :(對於版本> = 5.2)
laravel版本> = 5.2中不推薦使用 lists()方法,而應使用 pluck()方法:
$roles = $user
->roles
->pluck('id')
->toArray();
如果您需要一個字符串 (例如在blade中) ,則可以使用不帶toArray()附件的情況:
$roles = $user
->roles
->pluck('id');
更新 :(對於版本> = 5.2)
laravel版本> = 5.2中不推薦使用 lists()方法,而應使用 pluck()方法:
$roles = $user
->roles
->pluck('id')
->toArray();
如果您需要一個字符串 (例如在blade中) ,則可以使用不帶toArray()附件的情況:
$roles = $user
->roles
->pluck('id');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.