I got some trouble understanding how associations works with Sequelize. I am working on a project which have almost the same features that Reddit and therefore I am trying to associate the User table to the Post table as a 1:N associations.
User Model:
const { Sequelize, Model, DataTypes } = require ('sequelize');
const db = require('../config/db');
const Post = require('./Post')
class User extends Model{}
User.init({
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
username:{
type: DataTypes.STRING,
unique: true
},
email:{
type: DataTypes.STRING
},
password:{
type: DataTypes.STRING
},
isAdmin:{
type: DataTypes.BOOLEAN,
defaultValue: false
}
}, {sequelize: db, modelName:'User'}
);
User.hasMany(Post,{as: 'posts', foreignKey: 'id'});
User.sync();
module.exports = User;
Post Model:
const { Sequelize, Model, DataTypes } = require ('sequelize');
const db = require('../config/db');
const User = require('./User');
class Post extends Model{}
Post.init({
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
text:{
type: Sequelize.STRING
},
image:{
type: Sequelize.STRING
},
likes:{
type: Sequelize.INTEGER,
}
}, {sequelize: db, modelName:'Post'}
)
Post.sync();
module.exports = Post;
When I launch my app, I can see that it mention that post have the foreign key id but still I don't have hany column that link User to Post in my DB. What I am missing?
Executing (default): CREATE TABLE IF NOT EXISTS `Posts` (`id` INTEGER NOT NULL auto_increment , `text` VARCHAR(255), `image` VARCHAR(255), `likes` INTEGER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`), **FOREIGN KEY (`id`)** REFERENCES `Users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB;