mysql - Laravel 基于另一列对两列进行求和/减法
问题描述
+--+-------------+--------+------+------------+
|id|product_price|quantity|status|warehouse_id|
+--+-------------+--------+------+------------+
|1 |20.00 |2000 |1 |1 |
+--+-------------+--------+------+------------+
|1 |30.00 |3000 |1 |2 |
+--+-------------+--------+------+------------+
|1 |40.00 |4000 |1 |2 |
+--+-------------+--------+------+------------+
|1 |50.00 |5000 |2 |2 |
+--+-------------+--------+------+------------+
我有一个包含上述列的销售表
status = 1 表示产品已交付
status = 2 表示产品被退回
我有一个具有销售方法的仓库模型
public function sales () {
return $this->hasMany(Sale::class);
}
我想要的是?
我想得到每个仓库的总收入
预期成绩:
对于 id 1 的仓库sum = 20*2000
对于 id 2 的仓库sum = 30*3000 + 40*4000 - 50*5000
我尝试过使用withSum()
,但似乎很难做到雄辩的方式。我能做些什么吗?
解决方案
您可以使用DB::raw()
. 但是将生成的列添加到您的迁移中以获取总数并使用它会更有效withSum()
。
// Add something like this to the migration
$table->unsignedBigInteger('total')->storedAs('product_price * quantity');
// Then you can do
Warehouse::withSum('sales', 'total')->get();
推荐阅读
- c++ - U 没有命名类型 - 模板编译错误
- python-3.x - 更改时间列的数据类型-Pandas
- r - “上面列出了初始化中遇到的错误”(R)
- javascript - react-js中如何从组件中取出props数据?
- python - Scipy 和 Sklearn Yeo-Johnson 归一化结果不匹配
- python - 如何在所有列中找到一个值并将其放入新列中?
- ibm-mq - JMSWMQ2013:为队列管理器“QM1”提供的安全认证无效
- c++ - 使用 main() 包含来自其他 cpp(hpp) 文件的函数
- python - 从网络浏览器运行 selenium-python 脚本
- regex - 正则表达式用于替换字符以外的任何内容,多个空格和数字仅以空字符结尾