Sequelize关联查询无匹配记录时如何返回默认值
两种适配该业务场景的实现方案
方案一:业务层回退校验(推荐,低出错率)
该方案保留原有查询逻辑不动,在拿到查询结果后做判断,查不到匹配国家的有效域名时,单独查询默认有效域名补全返回值,逻辑边界最清晰,不会出现数据混杂问题。
修改后的代码实现:
async function getConfig(configId, country) { const config = await db.config.findOne({ attributes: ['id', 'version', /* 原有其他查询字段 */], where: { id: configId }, include: [ { required: false, model: db.domain, attributes: ['domain'], where: { country_code: country, isActive: true, }, }, ], }); // 匹配不到目标国家有效域名时,查询默认有效域名 if (!config?.domain?.length) { const defaultDomains = await db.domain.findAll({ attributes: ['domain'], where: { isActive: true, isDefault: true } }); config.domain = defaultDomains; } return config; }
该方案的优势:
- 不会出现目标国家已有匹配域名时,把默认域名混杂进返回结果的问题
- 逻辑拆分简单,后续扩展多层回退规则(比如先查区域域名、再查全球默认域名)的成本极低
- 完全依托原有查询索引,不会出现SQL条件复杂导致的索引失效问题
方案二:单查询条件合并(减少数据库交互次数)
该方案在原有关联查询的where条件中,通过子查询合并“目标国家域名”和“默认域名”的匹配规则,仅需要一次数据库查询就能拿到最终结果,适合性能敏感度高的场景。
代码实现:
const { Op } = require('sequelize'); async function getConfig(configId, country) { return await db.config.findOne({ attributes: ['id', 'version', /* 原有其他查询字段 */], where: { id: configId }, include: [ { required: false, model: db.domain, attributes: ['domain'], where: { isActive: true, [Op.or]: [ // 优先匹配目标国家的有效域名 { country_code: country }, { // 仅在目标国家无有效域名时,匹配默认域名 isDefault: true, id: { [Op.notIn]: db.sequelize.literal( `(SELECT id FROM domain WHERE country_code = '${db.escape(country)}' AND isActive = true)` ) } } ] }, }, ], }); }
使用注意事项:
- 必须对传入的country参数做转义处理,避免SQL注入风险
- 需要确认domain表在
country_code、isActive、isDefault字段上有合适的索引,避免子查询全表扫描 - 不要修改include配置的
required: false属性,否则如果没有匹配的域名,主表的config记录会被过滤掉
验证效果:传入参数
getConfig(1, 'tr')时,domain表无tr国家的活跃域名,查询会自动匹配isDefault标记的有效域名,最终返回结构和预期完全一致。
内容的提问来源于stack exchange,提问作者MegaRoks
相关产品推荐
相关产品推荐

