1

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.

Chaviweb
  • 11
  • 1

1 Answers1

1

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

Anatoly
  • 20,799
  • 3
  • 28
  • 42
  • Exactly. If you need another answer very similar to Anatoly's one, there's mine too [here](https://stackoverflow.com/questions/48946275/express-js-and-mysql-model-validation/48947228#48947228) – oniramarf Aug 07 '20 at 09:45