2016-07-18 154 views
0

我有我的數據庫中的表users,roles,它們的數據透視表role_user,和表comments。我正在嘗試做一個查詢,讓我可以讓所有用戶使用他們的角色進行評論。我不知道如何做到這一點,到目前爲止,我有一個查詢,看起來像這樣:Laravel嵌套渴望加載

$comments = Comment::with('user')->where('article_id', $articleId)->get(); 

隨着該查詢我得到每個評論的用戶,但是當我試圖添加的角色,就像這樣:

$comments = Comment::with('user', 'roles')->where('article_id', $articleId)->get(); 

或者,像這樣:

$comments = Comment::with('user.roles')->where('article_id', $articleId)->get(); 

但沒有奏效。 我已經安裝這樣的評論模型中的關係:

class Comment extends Model 
{ 

    public function user() 
    { 
     return $this->belongsTo('App\User'); 
    } 

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

更新

由於這是後端API端點,我發送數據到角前端,我剛纔檢查的結果在郵遞員那裏我得到了用戶角色數據與此查詢:

$comments = Comment::with('user.roles')->where('article_id', $articleId)->get(); 

然後,結果是這樣的:

"user":{"id":1, 
     "first_name":"admin", 
     "last_name":"admin", 
     "photo":"","email":"[email protected]", 
     "created_at":null, 
     "updated_at":"2016-06-14 16:19:35", 
     "roles":[{"id":1, 
        "name":"Admin", 
        "slug":"admin", 
        "description":null, 
        "parent_id":null, 
        "created_at":null, 
        "updated_at":null, 
        "pivot":{"user_id":1, 
          "role_id":1, 
          "created_at":"2016-06-14 14:14:25", 
          "updated_at":"2016-06-14 14:14:25", 
          "granted":1} 
}]}} 

但是,當我在我的角度控制器也CONSOLE.LOG我沒有得到角色的任何數據。

回答

1

試試這個它的工作對我來說

$comments = Comment::with(['user', 'roles'])->where('article_id', $articleId)->get(); 

你應該傳遞一個參數作爲數組預先加載。

謝謝