Sequelize自定义关联字段:MySQL视图用detail_id关联model_id
解决Sequelize自定义关联字段及视图关联问题
核心配置思路
Sequelize完全支持自定义关联字段,不用局限于默认的id关联,和Laravel的自定义关联逻辑类似,关键是在关联定义时明确指定源键和外键。
1. 视图与模型的关联配置
针对你的vw_monitor_jetty(MySQL视图,无id字段)关联file_storage_bunker的场景,需要在模型关联时指定:
- 对于
vw_monitor_jetty模型:用自身的detail_id作为关联的源键(sourceKey) - 对于
file_storage_bunker模型:用model_id作为关联的外键(foreignKey)
示例代码:
// vw_monitor_jetty模型定义中添加关联 vw_monitor_jetty.hasMany(file_storage_bunker, { sourceKey: 'detail_id', // 视图的关联字段 foreignKey: 'model_id', // 关联表的对应字段 as: 'fileBunkers' // 自定义关联别名,方便后续include调用 }); // 或者在file_storage_bunker模型中定义反向关联 file_storage_bunker.belongsTo(vw_monitor_jetty, { targetKey: 'detail_id', foreignKey: 'model_id', as: 'jettyMonitor' });
2. 过滤同detail_id不同model的记录
你提到file_storage_bunker存在同detail_id但不同model值的情况,完全可以在findAndCountAll的include配置中添加where条件来过滤特定的model值。
findAndCountAll调用示例
const result = await vw_monitor_jetty.findAndCountAll({ include: [ { model: file_storage_bunker, as: 'fileBunkers', // 要和关联定义的别名一致 where: { model: '你的目标model值' // 这里指定需要过滤的model值 }, required: false // 可选,设为false表示左关联,即使没有匹配记录也返回视图数据;设为true则是内关联 } ], // 其他分页、排序等配置 offset: 0, limit: 10 });
注意事项
- 确保
vw_monitor_jetty模型中正确映射了detail_id字段,视图字段要和模型定义一致 - 关联别名
as要在关联定义和include中保持统一,避免报错 - 如果需要同时过滤多个
model值,可以用[Op.in]操作符:model: { [Op.in]: ['值1', '值2'] }
内容的提问来源于stack exchange,提问作者yogithesymbian
相关产品推荐
相关产品推荐

