【问题标题】:Laravel query where field is less than sum of another field in related table (polymorphic relationship)Laravel查询其中字段小于相关表中另一个字段的总和(多态关系)
【发布时间】:2021-10-01 07:11:33
【问题描述】:

在 Laravel 中尝试查询发票表(表名:invoices),其中发票总额(字段名:net_total)大于为该发票支付的总和。设置为多态关系。

发票表:

public function transactions(){
    return $this->morphMany(TransactionAllocation::class, 'doc');
}

付款表:

public function doc()
{
    return $this->morphTo();
}

我尝试了似乎不起作用的查询。

Invoice::with('transactions')
        ->where('net_total', '>' ,'transactions.amount')
        ->get();

我根据下面的答案尝试了以下操作,这给了我关系的总和,但 where 条件失败

Invoice::withSum('transactions', 'amount')
                    ->where('net_total','>','transactions_sum_amount')
                    ->get();

结果截图 - https://prnt.sc/1favj7u 第二个数组不应该出现,因为它在 where 条件下失败。

关于我缺少什么的任何建议?

【问题讨论】:

    标签: sql laravel eloquent laravel-8


    【解决方案1】:

    由于您将有很多交易,如您所说,这是查询中缺少的部分。

    你可以试试withSum,例如

    InvoiceTest::withSum('transactions', 'amount')
        ->havingRaw('transactions_sum_amount < invoices.net_total')
        ->get();
    

    【讨论】:

    • 这可以带来总和。但它不满足 where 条件。它还引入了 net_total 的总和小于或等于总和的行。
    • 好的,所以transactions_sum_amount这部分很好,也许你在那里 2 net_total fields -&gt;where('invoices.net_total', '&gt;' ,'transactions_sum_amount')
    • 不,它也不起作用。这是结果的屏幕截图。第一个是对的。但是第二个不应该来。 prnt.sc/1favj7u
    • @Thaha 使用 ->whereColumn('net_total', '>' ,'transactions_sum_amount')
    • @JohnLobo 它会引发此错误。未找到列:1054 'where 子句中的未知列'transactions_sum_amount'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2019-09-26
    • 2021-11-21
    相关资源
    最近更新 更多