Laravel 5.5 如何获得 eloquent 关系计数?

Laravel 5.5 How to get eloquent relationship count?

我有下面定义的三个表

用户

Post

评论

这是用户模型User.php

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

这是我的post模型Post.php

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

问题:

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

有人可以帮我吗?提前致谢。

您可以为用户评论定义新的 hasManyThrough 关系 (docs):

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...
        );
    }
}

现在您可以统计每个用户的评论(Laravel docs):

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

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