Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add data in Sequelize migration script?

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.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()
}

}

like image 629
Fossmo Avatar asked Sep 11 '13 13:09

Fossmo


People also ask

How do I create a migration from a sequelizemeta table?

sequelize-cli db:migrate command looks on the SequelizeMeta table for any migration files which haven't run yet. Every migration lives on this table and inside migrations/ folder. This is the simplest migration you can create.

Where does Sequelize store the migration script name?

By default, sequelize stores the migration script name in the SequelizeMeta table so it can keep track of which migration has executed and which is not. However, we could change the default migration storage table name to something we prefer, in this example, we will change it to migrations.

What is the use of @Sequelize-CLI DB?

sequelize-cli db:migrate command looks on the SequelizeMeta table for any migration files which haven't run yet. Every migration lives on this table and inside migrations/ folder.

How to insert new rows into a SQL table using Sequelize?

To insert new rows into your SQL table, you need to first create a Sequelize Model object. In Sequelize, a Model is an object that represents your SQL table, giving information to Sequelize about the name, the columns, and their data types. From the Model, you can then call the create () method, which performs an INSERT SQL statement to your table.


1 Answers

I figured it out. Sequelize is available from migration.migrator.sequelize. It is possible to do something like this:

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();
    })
}
like image 116
Fossmo Avatar answered Oct 05 '22 07:10

Fossmo