【问题标题】:Sorting products by discount percentage按折扣百分比对产品进行排序
【发布时间】:2022-01-11 18:40:06
【问题描述】:
我正在尝试在我的 laravel 应用中按折扣百分比对产品进行排序。
我的产品表中有两列,即价格、折扣价格。我如何订购它们以便具有更高折扣的产品在订单中显示更高。我已经尝试过,但它不起作用
$products = DB::table('products')->get();
$sorted_products = $products->sortBy('price - discount_price');
请指教,谢谢。
【问题讨论】:
标签:
php
database
sorting
laravel-8
【解决方案1】:
您可以使用select 方法和DB::raw 将RAW SQL 组件添加到查询中。假设折扣是我们有兴趣获取所有字段 (*) 加上计算字段 price - discount 的货币单位折扣,我们将其称为 real_price。
$sorted_products = DB::table('product')
->select(DB::raw("*, price - discount as real_price"))
->orderBy("real_price")
->get();
这将构建以下 SQL 查询并执行它:
SELECT *, price - discount as real_price FROM product ORDER BY real_price;
如果折扣是百分比,您可以:
$sorted_products = DB::table('product')
->select(DB::raw("*, price * discount as real_discount"))
->orderBy("real_discount")
->get();
按更高的折扣值订购。