如何在Sequelize中通过自定义列名的关联表连接tableA与tableB?
在Sequelize中用自定义列名的关联表连接tableA和tableB的正确方式
针对对接现有数据库、所有列名均为自定义的场景,需要通过belongsToMany方法显式指定外键、关联表及对应列名,以下是具体实现步骤:
1. 修正模型语法错误
首先修复tableB模型中的语法问题(b_id定义后缺少逗号),同时需明确b_id为主键,否则Sequelize无法识别关联关系的目标主键:
module.exports = (sequelize, DataTypes) => { const tableB = sequelize.define("tableB", { b_id: {type: DataTypes.STRING, primaryKey: true}, new_data: {type: DataTypes.STRING} }, { freezeTableName: true, tableName: "tableB" }); return tableB }
2. 定义多对多关联关系
在模型中通过associate方法配置关联,可在每个模型文件中完成:
修改tableA模型
module.exports = (sequelize, DataTypes) => { const tableA = sequelize.define("tableA", { a_id: { type: DataTypes.BIGINT, primaryKey: true } }, { freezeTableName: true, tableName: "tableA" }); tableA.associate = (models) => { tableA.belongsToMany(models.tableB, { through: "linkingTable", // 指定关联表名 foreignKey: "a_id", // 关联表中对应tableA的列名 otherKey: "bId", // 关联表中对应tableB的列名 as: "relatedTableBs" // 查询时的自定义别名 }); }; return tableA }
修改tableB模型
module.exports = (sequelize, DataTypes) => { const tableB = sequelize.define("tableB", { b_id: {type: DataTypes.STRING, primaryKey: true}, new_data: {type: DataTypes.STRING} }, { freezeTableName: true, tableName: "tableB" }); tableB.associate = (models) => { tableB.belongsToMany(models.tableA, { through: "linkingTable", foreignKey: "bId", // 关联表中对应tableB的列名 otherKey: "a_id", // 关联表中对应tableA的列名 as: "relatedTableAs" // 查询时的自定义别名 }); }; return tableB }
关联表模型(linkingTable)
保持现有定义即可,需确保列名与数据库表完全一致:
module.exports = (sequelize, DataTypes) => { const linkingTable = sequelize.define("linkingTable", { bId: {type: DataTypes.STRING}, a_id: { type: DataTypes.BIGINT, primaryKey: true } }, { freezeTableName: true, tableName: "linkingTable" }); return linkingTable }
3. 关联查询示例
配置完成后,可通过自定义别名查询关联数据:
// 查询所有tableA及其关联的tableB数据,隐藏关联表中间字段 const tableAWithBs = await tableA.findAll({ include: [{ model: tableB, as: "relatedTableBs", through: { attributes: [] } }] }); // 查询单个tableB及其关联的tableA数据 const tableBWithAs = await tableB.findByPk("目标b_id值", { include: [{ model: tableA, as: "relatedTableAs", through: { attributes: [] } }] });
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

