我试着在我的拉拉应用中按折扣百分比对产品进行分类。我的产品表中有两列,即价格,discount_price。我怎样才能订购它们,使折扣较高的产品在订单中显示出更高的价格。我试过跟随,但不起作用
$products = DB::table('products')->get();
$sorted_products = $products->sortBy('price - discount_price');请给我指点,谢谢。
发布于 2022-01-11 19:12:07
可以使用select方法和DB::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();以更高的折扣价订购。
https://stackoverflow.com/questions/70671879
复制相似问题