【问题标题】:Eloquent count occurrence with where clause雄辩的计数出现与 where 子句
【发布时间】:2022-01-07 19:46:04
【问题描述】:

我正在尝试使用 Eloquent 进行简单的查询。我的test_registrants 表看起来像这样 我想用payment_status = 1添加值全部为user_id的新列

这是我使用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

我想要实现的是这个

那么我在这里做错了什么?谢谢

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

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

    当您为test_registrants 表上的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 的结果,以便计算特定组中的所有行。

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 2014-09-20
      • 2021-02-13
      • 2014-08-23
      • 1970-01-01
      • 2017-10-18
      • 2014-11-05
      • 2020-09-29
      • 2017-09-15
      相关资源
      最近更新 更多