I'm trying to return every posts with each one's author, and also every post's comments with it's author. this is what i did:
The controller:
$posts = Post::with('comments', 'user')->latest()->paginate(3);
The Post model:
public function comments() {
return $this->hasMany('App\Comment');
}
public function user() {
return $this->belongsTo('App\User');
}
The Comment model:
public function users() {
return $this->hasOne('App\User');
}
This returns every post with their authors and the comments but not the comment's author.
what else should i do??
Your Comment model:
public function users() {
return $this->hasOne('App\User');
}
Implies that a user entry in database would have a comment_id
field. But instead it should really have a user_id
field in the comments
database table:
public function user() {
return $this->belongsTo('App\User');
}
Now you can eager load authors of comments as well:
$posts = Post::with('comments.user', 'user')->latest()->paginate(3);
I'm not diving further into setting up an eloquent relationship. I hope you have correctly set it up.
Let's focus on the query:
Post::with('comments', 'user') -> Returns post with comments and who created it. Which is correct but now what you want.
Update Your Code
$posts = Post::with(['user',
'comments' => function($q) {
$q->with('user'); //Rename users to user in eloquent model. }
])->latest()->paginate(3);
Note: not tested. Try it out.