[英]Laravel nested eager loading
我的數據庫中有表users
, roles
,它們的數據透視表role_user
和表comments
。 我正在嘗試進行查詢,我可以讓所有具有其角色的用戶發表評論。 我不確定如何執行此操作,到目前為止,我的查詢看起來像這樣:
$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();
但這沒有用。 我已經在Comment模型中設置了如下關系:
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function roles()
{
return $this->hasManyThrough('App\Role', 'App\User');
}
}
更新資料
由於這是后端api端點,並且我將數據發送到Angular前端,因此我只檢查了郵遞員中的結果,並通過以下查詢獲取了用戶角色的數據:
$comments = Comment::with('user.roles')->where('article_id', $articleId)->get();
然后,結果如下所示:
"user":{"id":1,
"first_name":"admin",
"last_name":"admin",
"photo":"","email":"admin@coop.com",
"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}
}]}}
但是當我在Angular的控制器中進行console.log時,我沒有獲得任何角色數據。
試試這個對我有用
$comments = Comment::with(['user', 'roles'])->where('article_id', $articleId)->get();
您應該將參數作為數組傳遞,以方便加載。
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.