gpt4 book ai didi

mysql - Eloquent 中一个查询的多个求和

转载 作者:行者123 更新时间:2023-11-30 22:06:42 26 4
gpt4 key购买 nike

我正在尝试加快我的应用程序的速度,但对在单个 Eloquent 查询上执行操作有疑问。

我需要绘制一个包含不同总数的表格。

        $records = $this->finance
->where('company_id','=',$this->company_id)
->where(DB::raw('MONTH(date)'), '=', $month['month'])
->where(DB::raw('YEAR(date)'), '=', $year)
->where('financeaccounts_id', '=', $account);

$income = $records->where('type','=','Income')->sum('amount');
$expense = $records->where('type','=','Expense')->sum('amount');
$correction = $records->where('type','=','Correction')->sum('amount');

“收入”计算正确,但随后的“总和”却不正确。我猜测查询正在随着每个分配进行修改。我很感激你的帮助。谢谢

最佳答案

我认为更好的方法是只运行一个查询而不是 3 个,然后使用集合:

$records = $this->finance
->where('company_id','=',$this->company_id)
->where(DB::raw('MONTH(date)'), '=', $month['month'])
->where(DB::raw('YEAR(date)'), '=', $year)
->where('financeaccounts_id', '=', $account)
->get();

$income = $records->where('type', 'Income')->sum('amount');
$expense = $records->where('type', 'Expense')->sum('amount');
$correction = $records->where('type', 'Correction')->sum('amount');

在此代码中,您使用的是 sum() 集合方法,而不是查询生成器的 sum() 方法。这种方法不会创建三个查询,而只会创建一个。

关于mysql - Eloquent 中一个查询的多个求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41448539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com