2017-01-13 5 views
0

Laravel EloquentモデルManyToManyは自分の役割を持つすべてのユーザーを取得します

最近、Rawクエリを記述するのではなく、Laravelモデルや雄弁な関係で作業を始めました。

は今、私はこの問題に直面した:

私はUserモデル中関係だ:私はすることができる午前

public function users() 
{ 
    return $this->belongsToMany('App\User', 'users_has_roles', 'Roles_role_id', 'Users_id'); 
} 

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

そして役割モデル内の別の関係をすべてのユーザーを取得し、コントローラのコードを使用してエコーします。

$users = User::with('roles')->get(); 
foreach ($users as $user) { 
echo $user."<br>"; 
} 

{ "ID":18、 "名前": "Ajx6bK"、 "姓": "AwkMTWzgIB"、 "ユーザ名": "vt_2528"、 "のcreated_at": "2017年1月12日"、」 ["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 「role_id」:1、「role_name」:「Admin」、「role_description」:「ユーザー管理を含む、システム内のユーザー権限の大半」、 ""、 "名前": "hVUrMG"、 "姓": "fc72G7Ksw2"、 "ユーザー名": "vt_6610"、 "ピボット":{"ユーザーID":19、 "Roles_role_id":1}}} "、" created_at ":" 2017-01-12 "、" updated_at ":null、" roles ":[{" role_id ":2、" role_name ":" data-entry "、" role_description ":"のレコードを管理するシステム "" ピボット ":{" Users_id "20、" Roles_role_id ":2}}]}

問題: Iは、テーブルのフィールド変数のいずれかにアクセスすることができない "ロール"。 $ user-> roles-> role_nameまたはrole_descriptionです。あなたはそれに応じてそれらにアクセスする必要がありますので

答えて

1

$user->rolesは、ロールの配列である:

foreach ($user->roles as $role) { 
    echo $role->role_name; 
} 
+0

このコードは私にエラーを与えます: $ users = User :: wit h( 'roles') - > get(); foreach($ users-> roleを$ role){ echo $ role-> role_name; }で ErrorException HomeController.php行38: は未定義のプロパティ:それはないroles' '$ users->です\データベース\雄弁\コレクション:: $の役割 – ThomasThomaz

+0

を照らす' role' .. –

+0

は今、これを削除します:未定義 をプロパティ:Illuminate \ Database \ Eloquent \ Collection :: $ roles – ThomasThomaz

0

rolesは、オブジェクトの配列です、あなたはそれが

foreach($user->roles as $role){ 
    echo $role->role_name."<br/>"; 
} 

また設定および取得方法を学ぶループする必要がありますプロパティ値:http://php.net/manual/en/sdo.sample.getset.php

関連する問題