Sequelize多表关联查询问题:基于customer_id和book_id获取excerpt数据
修正后的Sequelize多级关联查询方案
第一步:确保模型关联正确定义
由于数据库未声明外键,需在Sequelize模型中手动指定关联的外键与目标键:
// Excerpt 与 Book 的关联 Excerpt.belongsTo(Book, { foreignKey: 'book_id', // Excerpt表中关联Book的字段 targetKey: 'id', // Book表对应的主键 as: 'book' // 关联别名,查询时需严格匹配 }); // Book 与 Library 的关联 Book.belongsTo(Library, { foreignKey: 'library_id', targetKey: 'id', as: 'library' }); // Library 与 Customer 的关联 Library.belongsTo(Customer, { foreignKey: 'customer_id', targetKey: 'id', as: 'customer' });
第二步:多级关联查询代码
通过嵌套include实现跨表关联,同时在对应层级添加where条件完成租户customer_id验证,并过滤指定book_id:
const targetCustomerId = 1; // 目标租户ID const targetBookId = 100; // 目标书籍ID const excerptRecords = await Excerpt.findAll({ where: { book_id: targetBookId // 直接过滤当前表的目标书籍ID }, include: [ { model: Book, as: 'book', include: [ { model: Library, as: 'library', include: [ { model: Customer, as: 'customer', where: { id: targetCustomerId // 多租户验证,确保数据属于指定租户 }, // 若无需返回Customer表字段,可添加 attributes: [] 隐藏 } ], // 若无需返回Library表字段,可添加 attributes: [] 隐藏 } ], // 若无需返回Book表字段,可添加 attributes: [] 隐藏 } ], // 可选:指定要返回的Excerpt表字段,例如 attributes: ['id', 'content', 'book_id'] });
关键注意点
- 关联定义的
as别名必须和查询include中的as完全一致,否则会触发关联匹配错误 - 租户验证的
where条件必须放在Customer层级的include内,确保只有属于该租户的片段数据被返回 - 多租户场景下不要添加
required: false,保持默认的required: true才能保证数据隔离,避免返回不属于当前租户的记录 - 隐藏不需要的关联表字段可以减少查询数据量,提升性能
内容的提问来源于stack exchange,提问作者SunAns
相关产品推荐
相关产品推荐

