Sequelize mssql: order by primary key and limit

让人想犯罪 __ 提交于 2019-12-12 19:21:21

问题


I want to run a query with results sort using the primary key and also limit the number of return results. For example:

return Things.findAll({ attributes: [ 'id', 'status', 'otherField' ], limit: 2, order: [['id', 'DESC']] })

when the query is build, it generate the following SQL statement:

... ORDER BY [Source].[id] DESC, [id] OFFSET 0 ROWS FETCH NEXT 2 ROWS ONLY

Because id is the primary key and the sort parameter is also id I get the following error:

'A column has been specified more than once in the order by list. Columns in the order by list must be unique.'

I am using sequelize 3.30.4 with tedious 2.0.0 connecting to a Microsoft SQL server 2017.

Thank you.


回答1:


The order array should contain arrays/tuples. Try this:

return Things.findAll({
  attributes: [
    'id',
    'status',
    'otherField'
  ],
  limit: 2,
  order: [ 
    ['id', 'DESC']
  ]
})



回答2:


By the default, Sequelize create createdAt column in each table. So you can handle this issue by doing like this:

return Things.findAll({
  attributes: [
    'id',
    'status',
    'otherField'
  ],
  limit: 2,
  order: [ 
    ['createdAt', 'DESC']
  ]
})

Do the sorting by using column createdAt as the param, the sorting result have same result as you do with id column



来源:https://stackoverflow.com/questions/45868651/sequelize-mssql-order-by-primary-key-and-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!