Issue Description
It's unclear about how to create associations in migration files when the models have associations with each other.
What was unclear/insufficient/not covered in the documentation
I read the migrations docs and the code of sequelize express-example.
The docs just explain how to create a model and migration file using sequelize-cli
. The thing is when people create models and migration files such as User
and Task
and define associations like this:
// user.js
// ...
User.associate = function(models) {
User.hasMany(models.Task);
}
// ...
// task.js
// ...
Task.associate = function(models) {
// Using additional options like CASCADE etc for demonstration
// Can also simply do Task.belongsTo(models.User);
Task.belongsTo(models.User, {
onDelete: "CASCADE",
foreignKey: {
allowNull: false
}
});
}
// ...
Now, the models have associations. But, the migration file DOES NOT have associations. This means even if the UserId
is added to the Task
model. But in the migration file, the Task
table doesn't have UserId
at this moment.
Here are the workflow steps I current use:
- Create migration and model files using
sequelize-cli
- Define the model and the associations manually based on my business logic.
- Back to modify the generated migration file, add the
UserId
column to xxx-create-task.js
file (This is where I'm not sure and confused. But I saw the express-example use this workflow)
So, what's the correct workflow to create associations in migration files?
If possible: Provide some suggestion on how we can enhance the docs
If I understand correctly, the migration file and the model are a different part. This means we have to keep both in sync manually, sequelize and sequelize-cli will not do it for us automatically.
Another issue is to create the join table, sequelize-cli
will not create the join table, right? If so, what's the best way to create this join table migration file?
It's different from the sequelize.sync()
API. For testing purposes, this API will create tables with correct associations, add UserId
column to the Task
table based on the models' associations we defined. Besides, it also create join table for many-to-many association too. It seems this API will keep the model and "migration" sync automatically
Additional context
I found a post about this in medium: https://medium.com/@andrewoons/how-to-define-sequelize-associations-using-migrations-de4333bf75a7
It seems the author uses the same workflow as mine
Issue Template Checklist
Is this issue dialect-specific?
Would you be willing to resolve this issue by submitting a Pull Request?