问题描述
我们正在尝试使用 Sequelize 在 PostgreSQL 中自动创建表.不幸的是,它不会将外键创建为约束.这是我的一个模型的示例:
We're trying to create tables automatically inside PostgreSQL using Sequelize. Unfortunately, it doesn't create the foreign keys as constraints. Here is an example of one of my models:
module.exports = function(schema, DataTypes) {
var definition = {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
deal_id: {
type: DataTypes.INTEGER
},
image: DataTypes.STRING,
};
var image = schema.define('Image', definition, {
tableName: 'images', // this will define the table's name
timestamps: false, // this will deactivate the timestamp columns
syncOnAssociation: true,
classMethods: {
getDefinition: function() {
return definition;
},
associate: function(_models) {
image.belongsTo(_models.Product, {
foreignKey: 'deal_id'
});
}
}
});
return image;
};
我做错了吗?
推荐答案
首先,ORM 在内部处理这种事情而不是在数据库中使用外键约束的情况并不少见.
First, it's not uncommon for ORMs to handle this kind of thing internally rather than by using foreign key constraints in the database.
其次,ORM 需要 一对 关联语句来触发您可能期望的所有内部处理,这并不罕见.
Second, it's not uncommon for ORMs to require a pair of association statements to trigger all the internal handling you might expect.
var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
, User = this.sequelize.define('User', { username: Sequelize.STRING })
User.hasMany(Task)
Task.belongsTo(User)
最后,Sequelize 实际上会将外键声明写入数据库,但前提是您还使用 onUpdate
或 onDelete
声明了某种动作(或不动作).
Finally, Sequelize will actually write foreign key declarations into the database, but only if you also declare some kind of action (or inaction) with onUpdate
or onDelete
.
要向列添加引用约束,您可以传递选项onUpdate 和 onDelete 到关联调用....
User.hasMany(Task, { onDelete: 'SET NULL', onUpdate: 'CASCADE' })
CREATE TABLE IF NOT EXISTS `Task` (
`id` INTEGER PRIMARY KEY,
`title` VARCHAR(255),
`user_id` INTEGER REFERENCES `User` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
);
这篇关于Sequelize 不会创建外键作为约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!