Eloquent 计算 where 子句的出现次数

Eloquent count occurrence with where clause

我正在尝试使用 Eloquent 进行简单查询。我的 test_registrants table 看起来像这样 我想添加值为 user_idpayment_status = 1

的新列

这是我使用 whereColumn

的查询
TestRegistrant::select(['test_registrants.*'])
            ->where('payment_status', 1)
            ->addSelect([
                'attempt' => TestRegistrant::select(DB::raw('count(*) as attempt'))
                    ->whereColumn('test_registrants.user_id', 'user_id')
                    ->where(function ($query) {
                        $query->where('payment_status', 1);
                    })
            ]);

但我得到了全部 user_id

我要实现的是这个

那么我做错了什么?谢谢

您的查询返回 3 的原因是因为它只是计算具有 payment_status = 1 的所有记录。 whereColumn() 无法正常工作,因为它没有反映正确的列。

当您为 test_registrants table 上的 user_id 列定义 alias 时,它应该可以工作。例如,您可以将其命名为:outer_user_id。我已经相应地更新了您的示例:

TestRegistrant::select(['test_registrants.payment_status', 'test_registrants.user_id as outer_user_id'])
  ->where('payment_status', 1)
  ->addSelect([
      'attempt' => TestRegistrant::selectRaw('count(*) as attempt')
          ->whereColumn('test_registrants.user_id', 'outer_user_id')
          ->where(function ($query) {
            $query->where('payment_status', 1);
          })
        ])
  ->get();

或者,您也可以查看 grouping 结果,以便计算特定组中的所有行数。