Skip to content
Advertisement

Laravel 5.5 How to get eloquent relationship count?

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.

Advertisement

Answer

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

class User
{
    public function comments()
    {
        return $this->hasManyThrough(
            'AppComment',
            'AppPost',
            '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 = AppUser::withCount('comments')->get();

foreach ($users as $user) {
    echo $user->comments_count;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement