当我们使用join方法时,通过id为root表顺序sorting

这下面的Sequelize工作罚款我没有使用order ,我想知道为什么我不能使用作为posts模式的根表的order ? 当我使用下面的代码,我得到这个错误:

 Unhandled rejection Error: 'posts' in order / group clause is not valid association 

但在channelVideoContainer等其他模型上工作正常

  models.posts.findAll({ where: { channelId: 1 }, include: [ { model: models.channelVideoContainer, include: [models.fileServerSetting] }, { model: models.channelMusicContainer, include: [models.fileServerSetting] }, { model: models.channelImageWithTextContainer, include: [models.fileServerSetting] }, { model: models.channelFilesContainer, include: [models.fileServerSetting] }, models.channelPlainTextContainer ], order: [ [{model: models.posts}, 'id', 'DESC'], ], limit: 5 }).then(function (result) { console.log(JSON.stringify(result)); }); 

您正在查看posts表格/模型,然后按posts模型中的列进行sorting,但是您在order中指定了“已join”表格。 这适用于您的其他模型,因为它们实际上已join(使用include选项)。 由于您在查询posts模型,您只需要传入您想要sorting的列的名称即可。 请参阅文档中的一些ORDER示例 。

 // just specify the 'id' column, 'post' is assumed because it is the queried Model order: [['id', 'DESC']], 

作为一个方面说明,您可能需要在include模型中指定required: false来执行LEFT JOIN以便行即使在连接表中没有匹配时也会返回。 如果你知道行将被返回(或者实际上是需要的),那么保持原样。

 { model: models.channelFilesContainer, include: [models.fileServerSetting], required: false, // LEFT JOIN the channelFilesContainer model },