laravel - Sum by cases using just Eloquent
问题描述
I have a model called Purchases that has a many-to-many relationship with Product model. I created a model to manage the table in the many-to-many relationship called PurchasedProduct. This model is related to an other model called Currency.
Purchases table: Id, number, created_at, updated_at.
Product_table: Id, description, created_at, updated_at.
Currency table: Id, code, name, ratio.
Product_Purchase table: Id, purchase_id, product_id, currency_id, quantity, price.
An User
can purchase several Products
then, he can pay in many Currencies
. To manage every transaction, I want to sum the total (quantity * price) by currency.
I've tried to do it with an accessor but all I can do is sum the product of quantity * price without consider the currency.
public function getTotalAttribute($value)
{
$transformers = $this->transformers();
return $transformers->sum(\DB::raw('quantity * price'));
}`
解决方案
您可以使用groupBy
public function getTotalAttribute($value)
{
$transformers = $this->transformers();
return $transformers->groupBy('currency_id')
->selectRaw('sum(quantity * price) as sum, currency_id')
->get();
}
推荐阅读
- python - 如何在数字海洋上上传我的 odoo 自定义模块?
- java - 如何在清单中制作一个带有第三方依赖 jar 的 jar(没有任何 ide)
- macos - 从最近的应用程序中删除 Dock 中的图标
- python - Python:将列表转换为变量中的逗号分隔值以传递 where IN 条件
- c# - 检查用户名是否在数据库中可用
- jquery - Firefox 浏览器上的 Dialogflow Messenger 高度自定义问题
- reactjs - Apollo 客户端 fetchPolicy 问题 - 查询调用了两次
- python - 在将数据输入 FFT 用于音频频谱分析仪之前,使用 python 将 wav 文件转换为 csv 文件
- ambiguous - NSPredicateEditorRowTemplate() 给出语法错误“表达式类型不明确,没有更多上下文”
- flutter - 如何创建一个价格变量,在展开时在每个列表图块中都有不同的值?