Add data in Sequelize migration script?

后端 未结 4 1937

How can I add data to a table in a Sequelize migration script? This is what I got:

module.exports = {
up: function(migration, DataTypes, done) {
    migration.cr         


        
4条回答
  •  遥遥无期
    2021-02-07 07:39

    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'),
    };
    

提交回复
热议问题