【问题标题】:Sum two columns in laravel eloquent在 laravel eloquent 中求和两列
【发布时间】:2020-08-24 23:28:43
【问题描述】:

我是 laravel 的新手,所以我对同一张表中两列的总和有一点问题。

对于列 sum(dug) 和列 sum(pot),我的回答应该是两位十进制数。这些列之间的加减法和其他操作无关紧要。我只想要 sum(dug) 和 sum(pot)...

我的代码是:

 public function getBalance() {
    $details = AnalyticalCard::select('sum(dug) as duguje, sum(pot) as potrazuje')
        ->where('firma', 001)
        ->where('komitent', 'V003')
        ->where('konto', 2020)
        ->get();

    return response()->json($details);
}

我的 SQL 查询是:

select 
    sum(dug) as duguje, sum(pot) as potrazuje 
from 
    fn_promet 
where 
    firma = 001 and komitent = 'V003' and konto = '2020'

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你的查询应该是

    $details = AnalyticalCard::select('sum(dug) as duguje, sum(pot) as potrazuje')
            ->where('firma', 001)
            ->where('komitent', 'V003')
            ->where('konto', 2020)
        ->select(DB::Raw('sum(dug) as duguje, SUM(pot) as potrazuje '))
            ->get();
    

    【讨论】:

    • txn,很好的解决方案
    【解决方案2】:

    您可以使用selectRaw。这是一个改编的例子:

        public function getBalance() {
        $details = DB::table('table')->selectRaw('sum(dug) as duguje, sum(pot) as potrazuje')
            ->where('firma', 001)
            ->where('komitent', 'V003')
            ->where('konto', 2020)
            ->get();
    
        return response()->json($details);
    

    【讨论】:

    • tnx,我会使用这个查询
    猜你喜欢
    • 2016-06-26
    • 1970-01-01
    • 2022-01-01
    • 2014-09-13
    • 2019-10-24
    • 2019-09-11
    • 1970-01-01
    • 2021-08-10
    • 2015-08-01
    相关资源
    最近更新 更多