我将如何更改此查询以适应 Laravel 的查询生成器?

How would I change this query to fit into Laravel's Query Builder?

我已尝试在 Laravel 中创建此查询,但仍然无法使其与查询生成器一起使用。它给我语法错误,但我可以 运行 它在表格中并且它 运行 平滑。

查询试图 运行:

select A.*, sum(RawAmt) as AmountOwed from (select Login, PatID,
if(length(ApptID) > 0, ApptID, VisitID) as VisitID,
ServiceDate,
TotalCharge,
InsurancePaid,
PrevPaid,
WriteOff,
Refund,
MiscDebit,
AmountOwed as RawAmt,
ApptTime,
ApptDate,
Physician,
isCopay,
HLocation from MDPay_AcctHist where Login='demo') A
group by PatID, VisitID

尝试使用 DB::select 和 DB::where 中的 DB::raw 语句执行此操作时出现语法问题;

任何关于尝试编写此代码以满足 laravels 规范的帮助都会有所帮助。

$subquery = DB::selectRaw('
        Login, PatID,
        if(length(ApptID) > 0, ApptID, VisitID) as VisitID,
        ServiceDate,
        TotalCharge,
        InsurancePaid,
        PrevPaid,
        WriteOff,
        Refund,
        MiscDebit,
        AmountOwed as RawAmt,
        ApptTime,
        ApptDate,
        Physician,
        isCopay,
        HLocation')
    ->from('MDPay_AcctHist')
    ->where('Login', '=', 'demo')
    ->toSql();

$result = DB::selectRaw('A.*, sum(RawAmt) as AmountOwed')
    ->from(DB::raw($subquery . ' as A'))
    ->groupBy('PatID', 'VisitID')
    ->get();