PPS*_*ein 43 node.js express sequelize.js
我正在尝试使用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']
});
};
Run Code Online (Sandbox Code Playgroud)
但问题是在渲染之后,所有数据都按如下方式排序.
46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, ....
Run Code Online (Sandbox Code Playgroud)
正如我发现的那样,它既没有按ID也没有名称.请帮我解决一下.
Jam*_*111 106
在续集中,您可以轻松地按子句添加顺序.
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']
});
};
Run Code Online (Sandbox Code Playgroud)
看看我是如何添加order对象数组的?
order: [
['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],
Run Code Online (Sandbox Code Playgroud)
编辑:
一旦在.then()承诺中收到对象,您可能必须对它们进行排序.查看关于根据自定义订单排序对象数组的问题:
如果你使用MySQL,你可以使用order by FIELD(id, ...) 方法:
Company.findAll({
where: {id : {$in : companyIds}},
order: sequelize.literal("FIELD(company.id,"+companyIds.join(',')+")")
})
Run Code Online (Sandbox Code Playgroud)
请记住,它可能会很慢。但应该比用 JS 手动排序更快。
您可以使用以下代码以非常间接的方式完成此操作:
exports.getStaticCompanies = function () {
var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
return Company.findAll({
where: {
id: ids
},
attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
order: sequelize.literal('(' + ids.map(function(id) {
return '"Company"."id" = \'' + id + '\'');
}).join(', ') + ') DESC')
});
};
Run Code Online (Sandbox Code Playgroud)
这在某种程度上是有限的,因为它的性能特征在几十条记录之后非常糟糕,但在您使用的规模上是可以接受的。
这将生成一个如下所示的 SQL 查询:
[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您想将数据按照升序或者降序基于特定的列,使用排序sequlize js,使用order的方法sequlize如下
// Will order the specified column by descending order
order: sequelize.literal('column_name order')
e.g. order: sequelize.literal('timestamp DESC')
Run Code Online (Sandbox Code Playgroud)
可能有点晚了,但想提一下方法。
基于 [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680] 的排序可以使用postgreSQL的 ARRAY_POSITION 函数完成。
const arr = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680];
const ord = [sequelize.literal(`ARRAY_POSITION(ARRAY[${arr}]::integer[], "id")`)];
return Company.findAll({
where: {
id: arr
},
attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
order: ord,
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58778 次 |
| 最近记录: |