在nodejs中查找所有sorting顺序

我试图从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'] }); }; 

但是问题出在渲染之后,所有的数据都按照如下进行sorting。

 46128, 53326, 2865, 1488, 45600, 61680, 49569, 1418, .... 

正如我所发现的,它既没有按照id也没有命名。 请帮我解决这个问题。

在续集中,您可以轻松地通过子句添加订单。

 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()承诺之内收到对象,您就可能需要对这些对象进行sorting。 检出有关基于自定义顺序排列对象数组的问题:

如何基于另一个数组的sorting对一组对象进行sorting?

在Sequelize的order子句中 ,我认为这是不可能的 ,因为据我所知,这些子句应该是适用于列表中每个元素的二进制操作。 (这也是有道理的,因为它通常是如何对列表进行sorting的。)

所以,一个订单子句可以做一些事情,例如通过recursion遍历它来询问“这两个元素哪一个更老? 而你的sorting不能简化为二元运算( compare_bigger(1,2) => 2 ),而只是一个任意的序列( 2,4,11,2,9,0 )。

当我用findAll来解决这个问题的时候,这里是我的解决scheme(在你返回的numbers结果中)

 var numbers = [2, 20, 23, 9, 53]; var orderIWant = [2, 23, 20, 53, 9]; orderIWant.map(x => { return numbers.find(y => { return y === x })}); 

其中返回[2, 23, 20, 53, 9] 。 我不认为我们可以做出更好的权衡。 你可以使用findOne遍历你的命令ID,但是当你执行的时候你会做n个查询。

你可以用下面的代码来完成这个工作:

 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') }); }; 

这是有限的,因为它的性能特点非常糟糕,超过了几十条logging,但在您使用的规模上是可以接受的。

这将产生一个如下所示的SQL查询:

 [...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])