首页 > 解决方案 > 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(),但似乎很难做到雄辩的方式。我能做些什么吗?

标签: mysqllaraveleloquent

解决方案


您可以使用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();

推荐阅读