Trying to create a todo list with sequelize but I always hava this error: "Cannot add foreign key constraint using Sequelize" Even looking for some clues in StackOverflow, somone can help?
ToDo Migration
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Todos', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
description: {
type: Sequelize.STRING,
allowNull: false,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
status_id: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Statuses',
key: 'id',
},
},
});
},
async down(queryInterface) {
await queryInterface.dropTable('Todos');
},
};
Status migration
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('Statuses', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
name: {
type: Sequelize.STRING,
allowNull: false,
},
});
},
async down(queryInterface) {
await queryInterface.dropTable('Statuses');
},
};
Relationship in models
// Status model
Status.associate = (models) => {
Status.belongsTo(models.Todo, { foreignKey: 'status_id', as: 'todo' });
};
// Todo model
Todo.associate = (models) => {
Todo.hasMany(models.Status, { foreignKey: 'status_id', as: 'statuses' });
};
If someone have any idea I'm really appreciate! Thanks