0

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;
El_Michel
  • 11
  • 5
  • You do? HasMany creates foreign key on target table(Post). `FOREIGN KEY (\`id\`) REFERENCES \`Users\` (\`id\`)` is the command that creates it. Check your database. You can view table information with the command `DESCRIBE Posts` – Darvesh Apr 11 '22 at 08:53
  • Thanks for you answer. I've checked my DB and and my Posts table don't have any column that links it with my User model. I think because it's refering to the same primary key `id` from post. Do I have to create an `user_id` column in my Post model to associate this two models? – El_Michel Apr 11 '22 at 09:48

1 Answers1

0

First, you need to indicate the correct value in the foreignKey option, it should be a field like user_id in Post model:

User.hasMany(Post,{as: 'posts', foreignKey: 'user_id'});

Second, you need to move association definitons and sync calls (and cross-refrences of models) from model modules outside. You need to register all models and only after that to define all their associations and the last action would be calling sync methods. See the question and my answer here to get an idea how to do it.

Anatoly
  • 20,799
  • 3
  • 28
  • 42