简体   繁体   English

如何对 Sequelize 中的查询结果进行排序?

[英]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:我正在尝试返回有序表单查询(升序或降序)的结果,我知道它是使用 order: ['columnName', sort order (ASC / DESC)] 完成的,当我只排序时我做得很好基于单列,但假设我有一个包含这些列的表:

product_id, price, offer_price, offer, description product_id、价格、offer_price、offer、描述

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).并且我想按价格或按offer_price 排序(offer_price 列取决于offer 列,也就是说,只有当offer 列的值为1 表示该产品确实在销售时,我才对offer_price 感兴趣)。

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' Product1:product_id = 1,price = 9,000,offer_price = 8,500,offer = 1,描述:'yy'

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

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

the query result in ascending order should be: product3, product2, product1.查询结果按升序排列应为: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)).由于 product3 正在打折并且是所有产品中的最低价格 (1,000),因此产品 2 如下(这个有 price_offer = 500 但不打折,因此采用正常价格 (2,000),最后是 product3 (8,500 ))。

How could I achieve this using Sequelize?我如何使用 Sequelize 实现这一目标? I can't find something to help me with the documentation.我找不到可以帮助我处理文档的东西。

You can use MySQL IF function like this:您可以像这样使用 MySQL IF function

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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