[英]Laravel Eloquent models ManyToMany get all users with their role
親愛的人們。
最近,我開始更多地使用Laravel模型和雄辯的關系,而不是編寫Raw查詢。
現在我遇到了一個問題:
我在用戶模型中得到了聯系:
public function roles()
{
return $this->belongsToMany('App\Role', 'users_has_roles', 'Users_id', 'Roles_role_id');
}
角色模型中的另一個關系:
public function users()
{
return $this->belongsToMany('App\User', 'users_has_roles', 'Roles_role_id', 'Users_id');
}
我能夠通過使用控制器中的代碼來檢索所有用戶並回顯它們:
$users = User::with('roles')->get();
foreach ($users as $user) {
echo $user."<br>";
}
{“ id”:18,“名稱”:“ Ajx6bK”,“姓氏”:“ AwkMTWzgIB”,“用戶名”:“ vt_2528”,“ created_at”:“ 2017-01-12”,“ updated_at”:null,“角色“:[{” role_id“:3,” role_name“:” Reporter“,” role_description“:”能夠管理系統中的報告。“,” pivot“:{” Users_id“:18,” Roles_role_id“:3 }}}} {“ id”:19,“ name”:“ NJYMCU”,“ surname”:“ ZGzjvpDAiP”,“ username”:“ vt_6443”,“ created_at”:“ 2017-01-12”,“ updated_at” :null,“ roles”:[{“ role_id”:1,“ role_name”:“ Admin”,“ role_description”:“擁有系統中的大部分用戶權限,包括用戶管理。”,“ pivot”:{“ Users_id “:19,” Roles_role_id“:1}}]} {” id“:20,”名稱“:” hVUrMG“,”姓“:” fc72G7Ksw2“,”用戶名“:” vt_6610“,” created_at“:” 2017 -01-12“,” updated_at“:null,”角色“:[{” role_id“:2,” role_name“:”數據輸入“,” role_description“:”能夠管理系統中的記錄。“,”樞紐”:{“ Users_id”:20,“ Roles_role_id”:2}}]}
問題: 我無法訪問表“角色”的任何字段變量。 $ user-> roles-> role_name或role_description。
$user->roles
是一組角色,因此您應該相應地訪問它們:
foreach ($user->roles as $role) {
echo $role->role_name;
}
roles
是對象數組,您需要對其進行循環
foreach($user->roles as $role){
echo $role->role_name."<br/>";
}
另請了解如何設置和獲取屬性值: http : //php.net/manual/zh/sdo.sample.getset.php
您正在對集合進行回顯,因此它將把它轉換為JSON。
但是,如果將集合轉換為數組並使用任何轉儲方法(dd或dump),您會發現現在很容易遍歷該數組以訪問角色。
$users = User::with('roles')->get(); dd($users->toArray());
這將輸出
array:4 [▼
0 => array:8 [▶]
1 => array:8 [▶]
2 => array:8 [▶]
3 => array:8 [▼
"id" => 4
"username" => "testcase1"
"email" => "test1@test.com"
"firstname" => "Test"
"lastname" => "One"
"created_at" => "2018-04-04 05:17:13"
"updated_at" => "2018-04-04 05:17:13"
"roles" => array:1 [▼
0 => array:5 [▼
"id" => 4
"name" => "user"
"created_at" => "2018-04-04 05:17:13"
"updated_at" => "2018-04-04 05:17:13"
"pivot" => array:2 [▼
"user_id" => 4
"role_id" => 4
]
]
]
]
]
要訪問角色名稱和描述,您可以像這樣對數組進行兩次for-each循環
$users = User::with('roles')->get();
foreach ($users->toArray() as $key => $value) {
foreach ($value['roles'] as $innerkey => $innervalue) {
echo $innervalue['role_id'];//for role id
echo $innervalue['role_name'];//for role name
echo $innervalue['role_description'];//for role description
}
}
exit;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.