【问题标题】:Eloquent relation count problems雄辩的关系计数问题
【发布时间】:2020-02-03 11:05:11
【问题描述】:

我目前遇到以下问题

$eloquentEntity->relation->count()

$eloquentEntity->relation()->count()

有时会返回两个不同的值(第一个有时为零)。奇怪的是,即使所有 $eloquentEntity 都是批量检索的,但有时值会有所不同。

$eloquentEntity 是使用从数据库中获取的

$eloquentEntities = EloquentEntity::with(['relation'])->get()

所以当count() 在关系集合上运行时,该关系中包含的所有内容都应该可用。

有人知道我做错了什么吗?

【问题讨论】:

  • 试试sizeof($eloquentEntity->relation)
  • 使用这个count($eloquentEntity->relation);
  • 您在使用$eloquentEntity->relation->count()之前是否已经检索到关系?如果是这样,它是否以任何方式受到限制,例如where 子句?

标签: database laravel eloquent


【解决方案1】:

您可以使用withCount() 方法计算关系数量。像这样的

$eloquentEntities = EloquentEntity::withCount('relation')->get();
foreach ($eloquentEntities as $row) {
    echo $row->relation_count; // to print relation count
}

您也可以查看docs了解更多信息

【讨论】:

    【解决方案2】:

    您可以使用 count 属性,例如:

      public function getReferalUsersAttribute()
        {
            return $this->hasMany('App\User', 'referal_id' , 'id')->count();
    
        }
    

    在你的模型中添加类似的属性

    protected $appends = [
            'referal_users'
        ];
    

    【讨论】:

      【解决方案3】:

      如果计数关系实体尝试这样的代码

      $posts = App\Post::withCount('comments')->get();
      foreach ($posts as $post) {
       echo $post->comments_count;
      }
      

      document

      【讨论】:

        【解决方案4】:

        我刚刚找到了解决方案:我们使用 UUID 作为主键,但忘记在模型上设置 public $keyType = 'string';。默认情况下,他们将键解释为整数,由于某种原因,这在大多数情况下都适用于 UUID。

        【讨论】:

          猜你喜欢
          • 2014-09-24
          • 2019-03-17
          • 2020-07-03
          • 2014-10-18
          • 2019-10-29
          • 1970-01-01
          • 2020-09-25
          • 2015-11-01
          相关资源
          最近更新 更多