繁体   English   中英

SUM(value) as value SQL 查询不工作

[英]SUM(value) as value SQL Query not working

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

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

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 :)

您可以直接使用sum方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM