Sequelize关联子查询中排序规则失效问题求助
问题原因及解决方案
你的问题出在Sequelize处理带limit/offset的主查询时,关联模型内的order配置不会生效,甚至填错字段不报错——因为这种场景下Sequelize默认用JOIN方式查询,关联模型的排序规则会被直接忽略。
解决方案1:给Version关联配置添加separate: true
这是最贴合你需求的方式:让Sequelize先完成主表(UserAccount)的分页查询,再单独为每个结果查询对应的Version数据,此时Version内的排序规则会正常生效。修改后的代码如下:
UserAccount.findAll({ attributes: ['user_id'], limit, offset, where: { system_usage_email_set: true, }, include: [ { model: Account, as: 'account', attributes: ['account_id', 'name'], required: true, include: [ { model: Site, as: 'sites', attributes: ['site_id', 'domain'], required: true, where: { is_active: true, }, include: [ { model: Version, as: 'versions', required: false, attributes: ['version_id', 'version', 'status', 'note', 'updated_at', 'config'], order: [['updated_at', 'DESC']], where: { status: { [Op.in]: ['SUCCESS'], }, updated_at: { [Op.between]: [startDate, endDate], }, }, // 添加该行开启单独查询 separate: true }, ], }, ], }, ], });
解决方案2:将排序规则移到主查询的order中
如果你希望主查询的分页逻辑也基于Version的updated_at排序,可以把规则放到主查询的order配置里,明确指定关联路径:
UserAccount.findAll({ attributes: ['user_id'], limit, offset, where: { system_usage_email_set: true, }, // 主查询添加排序规则 order: [ [{model: Account, as: 'account'}, {model: Site, as: 'sites'}, {model: Version, as: 'versions'}, 'updated_at', 'DESC'] ], include: [ { model: Account, as: 'account', attributes: ['account_id', 'name'], required: true, include: [ { model: Site, as: 'sites', attributes: ['site_id', 'domain'], required: true, where: { is_active: true, }, include: [ { model: Version, as: 'versions', required: false, attributes: ['version_id', 'version', 'status', 'note', 'updated_at', 'config'], where: { status: { [Op.in]: ['SUCCESS'], }, updated_at: { [Op.between]: [startDate, endDate], }, }, }, ], }, ], }, ], });
注意:这种方式会改变主表的分页逻辑——主查询会先按Version的updated_at排序,再执行分页,和你原本“先分页主表,再排序关联Version”的需求不同,需根据实际场景选择。
内容的提问来源于stack exchange,提问作者LiteralMetaphore
相关产品推荐
相关产品推荐

