node.js - 序列化迁移 : Adding a foreign key constraint to a column on same table

标签 node.js foreign-keys sequelize.js database-migration

因此,我尝试在迁移文件中创建一个对其自身具有外键约束的表。

我尝试了遵循 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/

相关文章:

node.js - i18Next - NodeJS - 如何在不重新加载服务器的情况下更改翻译

node.js - gulp-jade 报告错误,如 'Cannot read property ' xxx' of undefined'

mysql - FK 在创建表时导致崩溃

sql - SQL Server 中的外键 - 使用哪种样式?

javascript - Sequelize 和 Postgres - 无法实现外键约束

node.js - Sequelize 迁移外键名称

node.js - 更改nodejs临时目录

node.js - Sequelize where has NOT

python - SqlAlchemy - 按关系属性过滤

javascript - promise 链中的所有内容都必须是 promise 吗?