仅Mysql原始计数

时间:2018-08-29 10:37:26

标签: php mysql laravel

我在项目中使用PHP和Laravel框架。

以上代码可完美运行

$users = User::select([
            'users.id',
            'users.name',
            'users.company',
            'users.country',
            'users.city',
            'users.email',
            'users.created_at',
            \DB::raw('SUM(reservations.dolar) as dolar'),
            \DB::raw('count(reservations.confirmation) as confirmation'),
        ])->join('reservations','reservations.user_id','=','users.id')
        ->groupBy('reservations.user_id');

现在计算所有的Reservation.confirmation列,但我只想计算Reservation.confirmation列的值1

我如何编辑

\DB::raw('count(reservations.confirmation) as confirmation'),

此代码

2 个答案:

答案 0 :(得分:0)

您已尝试在https://laravel.com/docs/5.6/queries#joins的“高级连接条款”部分中看到,您可以在Join函数中添加条件

$users = User::select([
        'users.id',
        'users.name',
        'users.company',
        'users.country',
        'users.city',
        'users.email',
        'users.created_at',
        \DB::raw('SUM(reservations.dolar) as dolar'),
        \DB::raw('count(reservations.confirmation) as confirmation'),
    ])->join('reservations', function ($join) {
                              $join->on('reservations.user_id', '=', 'users.id')
                                   ->where('reservations.confirmation', '=', 1);
    })->groupBy('reservations.user_id');

答案 1 :(得分:0)

如果您希望所有款项dolar不取决于确认, 您可以使用'case'语句:

\DB::raw('sum(case when reservations.confirmation=1 then 1 else 0 end) as confirmation')

或子查询:

\DB::raw('(Select count(*) FROM reservations WHERE user_id = users.id AND confirmation=1) as confirmation')