sequelize - 从包含的模型中按列排序

sequelize - order by column from included model

我不知道如何按我包含的模型中的列进行排序。但我什至没有 returning 属性中的那个字段。如果可能的话,我只想按它订购。或者我可以 return 它,只要我能按它排序就不用。

const users = await db.User.findAll({
    raw: true,
    attributes: [
        'id',
        'first_name',
        'last_name',
        'email',
        'Permission.type'
    ],
    include: [
    {
        model: db.Permission,
        where: { id: { [Op.lte]: 2 } },
        attributes: [],
        order: [[{ model: db.Permission }, 'id', 'DESC']]
    }
    ]
});

include 块中,order 块现在什么都不做。但是我的权限模型中有一个名为 id 的属性,我想根据该属性对所有结果进行排序。如果有必要,我可以将 Permission.id 添加到我的 attributes 中。但是我试了还是不行。

只需将 order 选项从 include 移动到主要选项:

const users = await db.User.findAll({
    raw: true,
    attributes: [
        'id',
        'first_name',
        'last_name',
        'email',
        'Permission.type'
    ],
    include: [
    {
        model: db.Permission,
        where: { id: { [Op.lte]: 2 } },
        attributes: []
    }
    ],
    order: [[{ model: db.Permission }, 'id', 'DESC']]
});

也许您应该在 include 属性中注明 id