本文介绍了在Node.js中排序findAll排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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.

推荐答案

在序列化中,您可以轻松地添加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:

如何根据另一个数组的顺序对对象数组进行排序?

这篇关于在Node.js中排序findAll排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 12:13