php - 我如何更改此查询以适合 Laravel 的查询生成器?

标签 php mysql laravel eloquent

我尝试在 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 语句执行此操作时,出现语法问题;

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

最佳答案

$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();

关于php - 我如何更改此查询以适合 Laravel 的查询生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29953234/

相关文章:

php - 先前插入的值会在页面刷新时自动插入

mysql - 如何使用 bash 将字符添加到 CSV 中每条记录的可变数量字段?

mysql - Node js foreach循环中查询的问题

php - 在 Laravel Blade 中,脚本 @include 有效,但为什么 @push 不起作用?

php - 在 mySQL 中将日期值转换为会计/纳税年度

php - 如何检查 apache 和 php-fpm 配置是否合适(不要太高或太低)

php - 结合来自两个不同表的 SQL 值并对其使用算术

mysql - 如何根据列的重复值选择记录?

php - 如何在 Laravel 5 中使用输入名称创建存储文件夹和子文件夹

php - Laravel 查询生成器原始 AND 语句