Sequelize Migrations:向同一个表上的列添加外键约束

use*_*715 5 foreign-keys database-migration node.js sequelize.js

所以我试图在迁移文件中创建一个带有外键约束的表。

我尝试了我可以遵循的续集文档,下面是我尝试过的代码,我还尝试将外键引用移动到定义属性的位置,但它在那里也不起作用。有没有办法在这里做我想做的事?

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'
      }
    ))
  },
Run Code Online (Sandbox Code Playgroud)

Nat*_*ate 12

Shashikant Pandit 的答案很好,但它不跨数据库兼容。

我在使用该迁移时遇到了问题,因为我有一个 PostgreSQL 作为主数据库,还有一个用于测试的内存 SQLite 数据库。在测试环境中运行迁移(测试从空白数据库开始并运行迁移以获取当前数据)会在 SQLite 中产生错误。

这是一个使用addConstraint内置 Sequelizes 的版本,并且应该是跨数据库兼容的。

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'),
};
Run Code Online (Sandbox Code Playgroud)


use*_*715 2

我发现我做错了什么,当我应该引用不同的列时,我试图创建一个外键来在同一个表上引用自身。哎呀!