【发布时间】:2017-01-16 12:21:55
【问题描述】:
我正在使用 sequelize 创建一个自引用的 belongsToMany 关系,并将模型作为 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() 语句的位置,那么表中字段的名称也会颠倒。
【问题讨论】:
标签: node.js sequelize.js