【问题标题】:Laravel Eloquent subquery and count subquery resultsLaravel Eloquent 子查询和计数子查询结果
【发布时间】:2020-03-21 04:03:44
【问题描述】:

假设有一个Post 模型。它在其模型中定义了一个名为comments()hasMany 关系。

我正在尝试:

  • 获取 cmets 的计数
  • 属于一组特定的帖子,由 id 数组定义
  • cmets 在特定日期范围内发布的位置

我认为以下方法会起作用:

$ids = [1, 2, 3, 4];

$results = Post::whereIn('id', $ids)
    ->with(['comments'])
    ->whereHas('comments', function($q) {
       $q->whereMonth('created_at', Carbon::now()->month);
    })
    ->withCount('comments')
    ->get();

然后做

$count = array_sum($results->pluck('comments_count')->toArray());

查询的结果确实包含comments_count,所以它可以工作,$count 也可以工作。

但是子查询中的日期范围没有被应用,它计算所有个cmets。我错过了什么?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您需要将相同的条件/子查询传递给withCount 方法:

    ->withCount(['comments' => function($q) {
           $q->whereMonth('created_at', Carbon::now()->month);
        }])
    
    

    https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.html#method_withCount

    【讨论】:

      猜你喜欢
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      相关资源
      最近更新 更多