Laravel 在几个条件下使用求和
Laravel use sum with a few conditions
我有一个具有 price
、quantity
和 status
属性的 Sale 模型
我要return销售总收入table(下面的查询return就是我要的结果)
SELECT SUM(case when status = 1 then price * quantity when status = 2 then price * quantity * -1 else 0 end) as total
FROM sales;
我尝试使用 select(DB::raw())
但它没有 return 数字,因为我无法使用 sum()
函数
假设您有一个 销售 模型,尝试类似的东西:
$result = Sale::select(DB::raw('SUM(case when status = 1 then price * quantity when status = 2 then price * quantity * -1 else 0 end) as total'))
->get();
我有一个具有 price
、quantity
和 status
属性的 Sale 模型
我要return销售总收入table(下面的查询return就是我要的结果)
SELECT SUM(case when status = 1 then price * quantity when status = 2 then price * quantity * -1 else 0 end) as total
FROM sales;
我尝试使用 select(DB::raw())
但它没有 return 数字,因为我无法使用 sum()
函数
假设您有一个 销售 模型,尝试类似的东西:
$result = Sale::select(DB::raw('SUM(case when status = 1 then price * quantity when status = 2 then price * quantity * -1 else 0 end) as total'))
->get();