'Laravel relationship - many comments on one post and one user on one comment [duplicate]
I have a Post model:
$posts = Post::with('comments')->get();
and every comment has user_id row
I want to get the user with every comment, with relations.
My comments method in Post model
public function comments()
{
return $this->hasMany(Comment::class);
}
what is the best approach to get the user with comment?
final result:
{
'id': 1,
'title': 'some title',
'caption': 'some caption:,
'comments': [
{
'id': 1,
'text': 'some text',
'user_id': 1,
'user': { 'id':1, 'username': 'something', 'email': '[email protected] }
},
{
'id': 2,
'text': 'some text',
'user_id': 2,
'user': { 'id':2, 'username': 'something', 'email': '[email protected] }
},
]
}
Solution 1:[1]
You can do it in your query by
$posts = Post::with('comments.users')->get();
Solution 2:[2]
you can add with() to the model relation
should be like this
public function comments()
{
return $this->hasMany(Comment::class)->with('user');
}
please change the user to your model relation
I hope it's helpful
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abdul Haseeb Khan |
| Solution 2 | Ahmed Hassan |
