![](/img/trans.png)
[英]return all users each user with posts and each post with comments laravel
[英]Laravel - join comments ,posts, users
我正在嘗試返回每個作者的所有帖子,以及每個作者的評論。 這就是我所做的:
控制器:
$posts = Post::with('comments', 'user')->latest()->paginate(3);
郵政模型:
public function comments() {
return $this->hasMany('App\Comment');
}
public function user() {
return $this->belongsTo('App\User');
}
評論模型:
public function users() {
return $this->hasOne('App\User');
}
這將返回每個帖子及其作者和評論,但不返回評論的作者。
我還應該怎么辦?
我不會進一步探討建立雄辯的關系。 希望您已正確設置。
讓我們專注於查詢:
Post::with('comments', 'user') -> Returns post with comments and who created it. Which is correct but now what you want.
更新您的代碼
$posts = Post::with(['user',
'comments' => function($q) {
$q->with('user'); //Rename users to user in eloquent model. }
])->latest()->paginate(3);
注意:未經測試。 試試看。
您的評論模型:
public function users() {
return $this->hasOne('App\User');
}
暗示數據庫中的用戶條目將具有comment_id
字段。 但實際上,它應該在comments
數據庫表中確實有一個user_id
字段:
public function user() {
return $this->belongsTo('App\User');
}
現在,您也可以渴望加載評論的作者:
$posts = Post::with('comments.user', 'user')->latest()->paginate(3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.