【问题标题】:SUM(value) as value SQL Query not workingSUM(值)作为值 SQL 查询不起作用
【发布时间】:2021-07-04 13:28:04
【问题描述】:

所以我在 clientPurchases 类中有这个函数,它选择某个客户在某个月份和年份的价值总和并返回它,如果它为空返回 0。

我的错误是显示总数的变量“total”返回的值错误

public function purchasesCount($month_id, $year_id)
    {    
        $purchasesCount = ClientPurchases::select(DB::raw('SUM(value) AS value'))
        ->where('client_id', $this->id)
        ->whereYear('date', '=', $year_id)
        ->whereMonth('date', '=', $month_id)
        ->get();

        if(!empty($purchasesCount->value)){
            return $purchasesCount->value;
        }else{
            return 0;
        }
    }

然后在我的 show.blade 中,我试图做一个 foreach 来总结一张卡片中的所有客户

<div class="col-md-4">
                <div class="carde card-1">
                    <h3>Clientes</h3>
                    <?php 
                        $total = 0;
                        foreach($clients as $client){
                           $valor = $client->purchasesCount($month, $year);
                           $total += $valor; 
                        }
                    ?>
                       
                    <h4 class="valor">{{ $total }} €</h4>
                    <h4 class="mes">{{date('F', mktime(0, 0, 0, $month - 1, 10))}}</h4>
                    <br>
                </div>
                </div>

我是 laravel 的新手,所以非常感谢 tkx :)

【问题讨论】:

    标签: php html sql laravel


    【解决方案1】:

    你可以直接使用sum方法:

     $purchasesCount = ClientPurchases::
                where('client_id', $this->id)
                ->whereYear('date', '=', $year_id)
                ->whereMonth('date', '=', $month_id)
                ->sum('value');
    return $purchasesCount;
    

    【讨论】:

    • 以及如何调用我刀片上的“sumed”值? @OMR
    • 它只会返回你只需将上面的代码粘贴到函数中并循环调用函数的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2016-10-26
    • 2021-02-26
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多