使用whereHas而不是join将Sql Query转换为Eloquent

时间:2017-08-09 11:17:01

标签: laravel eloquent laravel-5.4 laravel-eloquent

我想使用whereHas而不是join

将此代码转换为Laravel Eloquent
SELECT count(*)
FROM
  (
     SELECT SEC_USER.ID, count(REPORT_EVENTS.USER_ID) AS counter
     FROM SEC_USER
     JOIN REPORT_EVENTS ON SEC_USER.ID = REPORT_EVENTS.USER_ID
     WHERE "PASSWORD" != '##NO_PASS##'
       AND "SYSTEM_ID" = 'CUS'
       AND "EVENT_TYPE" IN ('BILL','CHARGE')
       AND "RESULT_CODE" = '0'
     GROUP BY SEC_USER.ID,REPORT_EVENTS.USER_ID
     HAVING count(REPORT_EVENTS.USER_ID) > 2
  )

我尝试过的事情:

范围

public function scopeWithAtLeastTwoTransaction(Builder $query): Builder
{
    return $query->has('reportEvents')
        ->whereHas('reportEvents', function ($q) {
            $q->whereIn('event_type', ['BILL', 'CHARGE'])
                ->where('result_code', '0');
        });
}

使用

$report['count_of_users_with_more_than_two_transactions'] = \App\User::registered()->withAtLeastTwoTransaction()->count(‌​);

0 个答案:

没有答案