Laravel 5.5如何获得雄辩的关系计数?

问题描述 投票:0回答:1

我有三个表,定义如下

用户

  • id
  • 名称

发布

  • id
  • 文本
  • user_id

评论

  • id
  • 文本
  • post_id

这是用户模型User.php

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

这是我的帖子模型Post.php

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

问题:

我想使用雄辩的急切加载显示每位用户的评论数。

有人可以帮我吗?预先感谢。

php laravel eloquent eager-loading eloquent--relationship
1个回答
2
投票

您可以为用户的注释定义新的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;
}
© www.soinside.com 2019 - 2024. All rights reserved.