1
我创建了自引用belongsToMany关系,并使用作为through参数的模型进行了sequelize。Sequelize belongsToMany自引用不创建外键
但是,当它创建表时,它只会为其中一个关系创建一个外键。
型号:
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()语句的位置,那么表中字段的名称也会颠倒过来。