首页 文章

使用SequelizeJS使用外键编写迁移

提问于
浏览
22

The Background

我正在用SequelizeJS构建一个项目,这是一个流行的NodeJS ORM . 在设计架构时,似乎有两种策略:

我的理解是#1对于快速原型设计更好,但对于预计会随着时间的推移而发展并且 生产环境 数据需要能够在迁移中存活的项目而言,#2是最佳实践 .

这个问题与策略#2有关 .

The Question(s)

我的表有必须通过外键反映的关系 .

  • 如何通过Sequelize QueryInterface创建具有外键关系的表?

  • Sequelize需要哪些列和帮助程序表?例如,似乎需要特定的列,例如createdAt或updatedAt .

2 回答

  • 25

    如何通过Sequelize QueryInterface创建具有外键关系的表?

    .createTable() 方法接受列的字典 . 您可以在documentation for .define()中查看有效属性列表,特别是通过查看params表中的 [attributes.column.*] 行 .

    要创建具有外键关系的属性,请使用“references”和“referencesKey”字段:

    例如,以下内容将创建一个 users 表,以及一个引用users表的 user_emails 表 .

    queryInterface.createTable('users', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      }
    }).then(function() {
      queryInterface.createTable('user_emails', {
        userId: {
          type: Sequelize.INTEGER,
          references: { model: 'users', key: 'id' }
        }
      })
    });
    

    sequelize需要哪些列和帮助程序表?例如,似乎需要特定的列,例如createdAt或updatedAt .

    看起来标准模型将为每个表预期 idupdatedAtcreatedAt 列 .

    queryInterface.createTable('users', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      createdAt: {
        type: Sequelize.DATE
      },
      updatedAt: {
        type: Sequelize.DATE
      }
    }
    

    如果在模型上设置paranoid to true,则还需要 deletedAt 时间戳 .

  • 5

    我想提供另一个 more manual alternative 因为在使用手动迁移和queryInterface时遇到了以下问题:迁移文件夹中有2个文件,如此

    migrations/create-project.js
    migrations/create-projectType.js
    

    因为 projectprojectTypeId 它引用了 projectType ,由于文件的顺序而没有创建,这导致了错误 .

    我通过在创建两个表之后添加外键约束来解决它 . 在我的情况下,我决定在 create-projectType.js 内写它:

    queryInterface.createTable('project_type', {
      // table attributes ...
    })
    .then(() => queryInterface.addConstraint('project', ['projectTypeId'], {
      type: 'FOREIGN KEY',
      name: 'FK_projectType_project', // useful if using queryInterface.removeConstraint
      references: {
        table: 'project_type',
        field: 'id',
      },
      onDelete: 'no action',
      onUpdate: 'no action',
    }))
    

相关问题