因此,我尝试在迁移文件中创建一个对其自身具有外键约束的表。
我尝试了遵循 sequelize docs 的方法下面是我尝试过的代码,我还尝试将外键引用移动到定义属性的位置,但它在那里也不起作用。有办法在这里做我想做的事吗?
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('comments', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
root_id: {
defaultValue: null,
type: Sequelize.INTEGER
},
parent_id: {
defaultValue: null,
type: Sequelize.INTEGER
},
}).then(() => queryInterface.addConstraint(
'comments',
['root_id'],
{
type: 'foreign key',
name: 'root_id_fk',
references: {
table: 'comments',
field: 'root_id'
},
onDelete: 'cascade',
onUpdate: 'cascade'
}
)).then(() => queryInterface.addConstraint(
'comments',
['parent_id'],
{
type: 'foreign key',
name: 'parent_id_fk',
references: {
table: 'comments',
field: 'parent_id'
},
onDelete: 'cascade',
onUpdate: 'cascade'
}
))
},
最佳答案
Shashikant Pandit 的答案很好,但它不跨数据库兼容。
我在使用该迁移时遇到了问题,因为我有一个 PostgreSQL 作为主数据库,还有一个用于测试的内存 SQLite 数据库。在测试环境中运行迁移(测试从空白数据库开始并运行迁移以获取当前数据)会在 SQLite 中产生错误。
这是一个使用 Sequelizes addConstraint
内置的版本,并且应该是跨数据库兼容的。
module.exports = {
up: (queryInterface, Sequelize) => queryInterface
.addConstraint('app_users', {
type: 'UNIQUE',
fields: ['email', 'column2', 'column3'],
name: 'unique_user_email',
}),
down: (queryInterface, Sequelize) => queryInterface
.removeConstraint('app_users', 'unique_user_email'),
};
关于node.js - 序列化迁移 : Adding a foreign key constraint to a column on same table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54895133/