Chaviweb
Chaviweb

Reputation: 11

Why the Associations do not work in sequelize?

I need to know why my code isn't working. I'm trying to make a cart table which is going to have a foreign key userId and productId. To achieve that, in my product model and user I do what I follow:

User.hasMany(Car,{
    primaryKey:'userId'
})

module.exports=User;

  Product.hasMany(Car,{
      primaryKey:'productId'
  })

module.exports = Product;

in Car model I have:

 const {Model, DataTypes}=require('sequelize');
    const sequelize=require('../config/database');
    const Product=require('./Product');
    const User=require('./User');
    
    class Car extends Model{}
    
    Car.init({
        id:{
            primaryKey:true,
            allowNull:false,
            type:DataTypes.UUID,
            defaultValue:DataTypes.UUIDV1
        }
    },{
       sequelize,
       modelName: 'car'
    });
    
    module.exports=Car;

I'm getting this mistake:

enter image description here

I need help.

Upvotes: 1

Views: 142

Answers (1)

Anatoly
Anatoly

Reputation: 22758

You should register all models in Sequelize and only after that register their associations. Also don't import models to each other model files. Define associate function in each model to register associations. See my answer

Upvotes: 1

Related Questions