我想使用whereHas而不是join
将此代码转换为Laravel EloquentSELECT 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();