我正在创建一个自引用的 belongsToMany 关系,sequelize 将模型作为 through 参数。
然而,当它创建表时,它只为其中一个关系创建一个外键。
型号:
const client = sequelize.define('client', {
ClientId: {
type: DataTypes.UUID,
primaryKey: true,
allowNull: false,
defaultValue: DataTypes.UUIDV4()
},
AccessMode: {
type: DataTypes.ENUM('allow_all', 'deny_all', 'selective'),
allowNull: false
}
}, {
classMethods: {
associate: function (models) {
// Tons of other relationships here
client.belongsToMany(models.client, {
through: models.clientAccess,
as: 'clientsWithAccess',
foreignKey: 'ClientId'
});
client.belongsToMany(models.client, {
through: models.clientAccess,
as: 'accessToClients',
foreignKey: 'AccessingClientId'
});
}
}
});
直通模型:
const clientAccess = sequelize.define('clientAccess', {
Access: {
type: DataTypes.ENUM('allow', 'deny'),
allowNull: false
}
}, {
timestamps: false
});
结果表只有 AccessMode 和 AccessingClientId 列。出于某种原因,AccessingClientId 被设置为主键。
如果我切换 belongsToMany() 语句的位置,那么表中字段的名称也会颠倒过来。
最佳答案
这是使用 belongsToMany() 方法的 otherKey 属性解决的。
client.belongsToMany(models.client, {
through: models.clientAccess,
as: 'clientsWithAccess',
foreignKey: 'ClientId',
otherKey: 'AccessingClientId'
});
client.belongsToMany(models.client, {
through: models.clientAccess,
as: 'accessToClients',
foreignKey: 'AccessingClientId',
otherKey: 'ClientId'
});
有了这个,表就在数据库中正确创建了。
关于node.js - Sequelize belongsToMany 自引用不创建外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39393119/