我正在嘗試在我的 laravel 應用程式中按折扣百分比對產品進行排序。我的產品表中有兩列,即價格、折扣價格。我如何訂購它們以便具有更高折扣的產品在訂單中顯示更高。我試過跟隨但它不起作用
$products = DB::table('products')->get();
$sorted_products = $products->sortBy('price - discount_price');
任何指標PLZ,謝謝。
uj5u.com熱心網友回復:
您可以使用該select方法并將DB::rawRAW 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://www.uj5u.com/qukuanlian/408764.html
標籤:
上一篇:結合嵌套和外部字典來制作資料框PandasPython
下一篇:如何在JPA/Hibernate中使用@JsonManagedReference和@JsonBackReference創建3向雙向關系
