0
votes

I have three tables as define below

User

  • id
  • name

Post

  • id
  • text
  • user_id

Comments

  • id
  • text
  • post_id

This is User model User.php

class User
{
     public function post()
    {
       return $this->hasMany(Post::class);
    }   
}

This is my post model Post.php

    class Post
    {
       public function comments()
       {
          return $this->hasMany(Comment::class);
       }   
   }

Issue:

I want to display no.of comments per user using eloquent eager loading.

Can anyone help me with that? Thanks in advance.

1

1 Answers

2
votes

You may define a new hasManyThrough relationship (docs) for user's comments:

class User
{
    public function comments()
    {
        return $this->hasManyThrough(
            'App\Comment',
            'App\Post',
            'user_id', // Foreign key on posts table...
            'post_id', // Foreign key on comments table...
            'id', // Local key on users table...
            'id' // Local key on posts table...
        );
    }
}

Now you can count each user's comments (Laravel docs):

$users = App\User::withCount('comments')->get();

foreach ($users as $user) {
    echo $user->comments_count;
}