Home > Enterprise >  Laravel relationship - many comments on one post and one user on one comment
Laravel relationship - many comments on one post and one user on one comment

Time:04-10

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] } 
    }, 
  ] 
}

CodePudding user response:

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

CodePudding user response:

You can do it in your query by

$posts = Post::with('comments.users')->get();
  • Related