I am starting with sequelize and was following their video tutorial online. After running
node_modules/.bin/sequelize model:create --name User --attributes username:string
node_modules/.bin/sequelize model:create --name Task --attributes title:string
which created the migration files for create user and create task. Then I had to add the associations to each model as follow:
// user.js
classMethods: {
associate: function(models) {
User.hasMany(models.Task);
}
}
// task.js
classMethods: {
associate: function(models) {
Task.belongsTo(models.User);
}
}
However, the migration files for creating the tables for user and task are already created. Do i have to manually update them to add the relationships? "migration:create" command creates the migration skeleton file. Do I manually fill out the skeleton files or is there a way to automatically create the complete migration file besides model creation?
P.S i have seen the following stackoverflow question: How to auto generate migrations with Sequelize CLI from Sequelize models?
To create a migration, execute db-migrate create with a title. node-db-migrate will create a node module within ./migrations/ which contains the following two exports: exports. up = function (db, callback) { callback(); }; exports.
You can create a separate migration from an empty migration file. I did that when I needed to add a few extra columns to a table.
sequelize migration:create --name users
Then in my new migration file.
module.exports = {
up: function (queryInterface, Sequelize) {
queryInterface.addColumn(
'Users',
'url',
Sequelize.STRING
);
},
down: function (queryInterface, Sequelize) {
queryInterface.removeColumn(
'Users',
'url',
Sequelize.STRING
);
}
};
Then just run the migrations.
sequelize db:migrate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With