简体   繁体   中英

Sorting products by discount percentage

I am trying to sort products by discount percentage in my laravel app. I have two columns in my products table ie price, discount_price. How can I order order them so that products with higher discount shows up higher in order. I've tried following but it doesn't work

$products = DB::table('products')->get();
$sorted_products = $products->sortBy('price - discount_price');

Any pointers plz, thanks.

You can use the select method and DB::raw to add a RAW SQL component to the query. Assunming that discount is the discount in currency units we are interested in fetching all the fields ( * ) plus the calculated field price - discount which we will call real_price .

$sorted_products = DB::table('product')
                       ->select(DB::raw("*, price - discount as real_price"))
                       ->orderBy("real_price")
                       ->get();

This will build the following SQL query and execute it:

SELECT *, price - discount as real_price FROM product ORDER BY real_price;

If the discount is as percentage you could:

$sorted_products = DB::table('product')
                       ->select(DB::raw("*, price * discount as real_discount"))
                       ->orderBy("real_discount")
                       ->get();

Which would be ordered by higher discount value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM