【问题标题】:Laravel 5.5 How to get eloquent relationship count?Laravel 5.5 如何获得雄辩的关系计数?
【发布时间】:2020-02-17 18:03:14
【问题描述】:

我有如下定义的三个表

用户

  • 身份证
  • 姓名

发帖

  • 身份证
  • 文字
  • user_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);
       }   
   }

问题:

我想使用 eloquent eager loading 显示每个用户的 cmets 数量。

谁能帮我解决这个问题?提前致谢。

【问题讨论】:

    标签: php laravel eloquent eager-loading eloquent-relationship


    【解决方案1】:

    您可以为用户的 cmets 定义一个新的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...
            );
        }
    }
    

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

    $users = App\User::withCount('comments')->get();
    
    foreach ($users as $user) {
        echo $user->comments_count;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-18
      • 2020-12-02
      • 2012-10-23
      • 2021-05-22
      • 2015-03-14
      • 2018-11-28
      • 2015-01-11
      • 2021-06-03
      • 2020-03-26
      相关资源
      最近更新 更多