我正在尝试使用 sequelize 从数据库中输出所有对象列表,如下所示,并希望在 where 子句中添加 id 时对数据进行排序。
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']
});
};
但问题是渲染后,所有数据整理如下。
46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....
我发现,它既不是按 id 也不是按名称排序的。请帮我解决一下。
最佳答案
在 sequelize 中,您可以轻松添加 order by 子句。
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
数组的?
order: [
['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],
编辑:
在 .then()
promise 中收到对象后,您可能必须对其进行排序。查看这个关于根据自定义顺序对对象数组进行排序的问题:
How do I sort an array of objects based on the ordering of another array?
关于node.js - 在nodejs中 Sequelize findAll排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36259532/