简体   繁体   中英

How to sort the result of a query in Sequelize?

I am trying to return the result of an ordered form query (ascending or descending), I know it is done using order: ['columnName', sort order (ASC / DESC)], I have done well when I am only sorting on base to a single column, but suppose I have a table with these columns:

product_id, price, offer_price, offer, description

and I want to sort by price or by offer_price (the offer_price column depends on the offer column, that is, I am interested in the offer_price only if the offer column has a value of 1 which indicates that this product is really on sale).

How could I do so that the results are returned to me ordered, by price or by price_offer, that is, if a product is on sale, I have to take into account the price_offer at the time of ordering, and if it is not on sale then I should take the normal price.

For example:

Product1: product_id = 1, price = 9,000, offer_price = 8,500, offer = 1, description: 'yy'

Product2: product_id = 2, price = 2,000, offer_price = 500, offer = 0, description: 'bbb'

Product3: product_id = 3, price = 1,500, offer_price = 1,000, offer = 1, description: 'ccccc'

the query result in ascending order should be: product3, product2, product1. since product3 is on sale and is the lowest price of all (1,000), product 2 is the following (this has a price_offer = 500 but is not on sale, so the normal price is taken (2,000), and finally the product3 (8,500)).

How could I achieve this using Sequelize? I can't find something to help me with the documentation.

You can use MySQL IF function like this:

 order: [sequelize.literal('(IF(offer = 1, offer_price, price))'), sort order (ASC / DESC)]

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