在nodejs中续集findAll排序顺序 [英] sequelize findAll sort order in nodejs
问题描述
我正在尝试使用 sequelize 从数据库中输出所有对象列表,如下所示,并希望在 where 子句中添加 id 时对数据进行排序.
I'm trying to output all object list from database with sequelize as follow and want to get data are sorted out as I added id in where clause.
exports.getStaticCompanies = function () {
return Company.findAll({
where: {
id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
},
attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
});
};
但问题是渲染后,所有数据整理如下.
But the problem is after rendering, all data are sorted out as follow.
46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....
我发现,它既不是按 id 也不是按名称排序的.请帮我解决一下.
As I found, it's neither sorted by id nor name. Please help me how to solve it.
推荐答案
在 sequelize 中,您可以轻松添加 order by 子句.
In sequelize you can easily add order by clauses.
exports.getStaticCompanies = function () {
return Company.findAll({
where: {
id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
},
// Add order conditions here....
order: [
['id', 'DESC'],
['name', 'ASC'],
],
attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
});
};
看看我是如何添加对象的 order
数组的?
See how I've added the order
array of objects?
order: [
['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],
在 .then()
承诺中收到对象后,您可能必须对其进行排序.查看这个关于根据自定义顺序对对象数组进行排序的问题:
You might have to order the objects once they've been recieved inside the .then()
promise. Checkout this question about ordering an array of objects based on a custom order:
这篇关于在nodejs中续集findAll排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!