繁体   English   中英

如何在已经生成的续集模型中添加其他属性?

[英]How to add additional attributes to a sequelize model after it has already been generated?

这是可能的,还是必须对整个项目进行核爆并重做?

示例:我想在 dog 表中添加“breedId”列以引用模型“Breeds”

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Dog', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      name: {
        type: Sequelize.STRING(50),
        allowNull: false
      },
      description: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Dog');
  }
};

由于您似乎正在使用迁移,因此您将很容易添加到您的表中。

创建另一个迁移,向上使用 queryInterface.addColumn(tableName: string, columnName: string, options: object),向下使用 queryInterface.removeColumn(tableName: string, columnName: string)。

如果您使用 sequelze.sync() 从模型构建表,您的选择会更糟。 您需要将 {force: true} 传递给 .sync() 方法,该方法将在使用模型中的属性重建它们之前删除当前表。 或者,为了保留数据,您可以通过手动将列和外键约束添加到数据库来省略 {force: true},并将相应的属性添加到模型中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM