在Sequelize迁移脚本中添加数据?

Fos*_*smo 16 node.js sequelize.js

如何在Sequelize迁移脚本中向表中添加数据?这就是我得到的:

module.exports = {
up: function(migration, DataTypes, done) {
    migration.createTable(
        'person',
        {
            name: DataTypes.STRING,
            age: DataTypes.INTEGER
        },
        {
            charset: 'latin1' // default: null
        }
    );
    // I want to insert person and age.
    migration.insert(???);
    done()
},
down: function(migration, DataTypes, done) {
    migration.dropTable('queue');
    done()
}
Run Code Online (Sandbox Code Playgroud)

}

Fos*_*smo 16

我想到了.Sequelize可从migration.migrator.sequelize获得.可以做这样的事情:

up: function (migration, DataTypes, done) {
    migration.createTable(
        'Person',
        {
            name: DataTypes.STRING,
            age: DataTypes.INTEGER,
        }
    ).success(function () {
        migration.migrator.sequelize.query("insert into person (name, age) values ('Donald Duck', 60)");
        done();
    });
},
down: function (migration, DataTypes, done) {
    migration.dropTable(
      'Person'
    ).then(function() {
      done();
    })
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*ble 12

在最新版本的续集中,这已经改变了,现在应该是

migration.createTable(
    'Person',
    {
        name: DataTypes.STRING,
        age: DataTypes.INTEGER,
    }
).then(function () {
    migration.sequelize.query("insert into person (name, age) values ('Donald Duck', 60)");
    done();
});
Run Code Online (Sandbox Code Playgroud)


Dio*_*ves 5

实际上,仅运行查询不是一个好主意。queryInterface现在具有create()和bulkCreate()。

'use strict';
module.exports = {
  up: function(queryInterface, Sequelize) {
    return queryInterface.bulkInsert('roles', [{
      label: 'user',
      createdAt: new Date(),
      updatedAt: new Date()
    }, {
      label: 'admin',
      createdAt: new Date(),
      updatedAt: new Date()
    }]);
  },
  down: function(queryInterface, Sequelize) {
    return queryInterface.bulkDelete('roles', null, {});
  }
};
Run Code Online (Sandbox Code Playgroud)

这将返回sequelize-cli预期的承诺。

来源(改编):https : //github.com/sequelize/sequelize/issues/3210


xab*_*xab 5

In sequelize version 4.41.2, when you use ES6+ and you want to do more complex insertions within migration you could make the up an async function which creates your table and then inserts the necessary data into the table. To ensure that the migration either succeeds OR fails without making any changes a transaction is used for every interaction with sequelize. Another important thing to note is that up must return a Promise.

Example of creating a table -> fetching data from other table -> modifying fetched data -> inserting modified data to new table:

module.exports = {
    up: (queryInterface, Sequelize) => queryInterface.sequelize.transaction(async (transaction) => {
        await queryInterface.createTable('person', {
            id: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: Sequelize.INTEGER,
            },
            name: {
                type: Sequelize.STRING,
            },
            age: {
                type: Sequelize.STRING,
            },
        }, { transaction });
        // Returns array [[results], { /** result obj */ }]
        const [dogs] = await queryInterface.sequelize.query('SELECT * FROM public."Dogs";', { transaction });
        // prepare data
        const metamorphed = dogs.map(({ name, age }) => ({
            name,
            age: parseInt((age * 7), 10),
        }));
        return queryInterface.bulkInsert('person', metamorphed, { transaction });
    }),
    down: queryInterface => queryInterface.dropTable('person'),
};
Run Code Online (Sandbox Code Playgroud)