Friday, 14 April 2017

Sequelize Associations Failing

I'm trying to associate my Product model with my User model. However, when trying to associate a product with a user, I get the following error: No column UserId exists.

To fix the problem, I added a UserId column in Products table, and made it a foreign key field referencing User:id. After running that: I get the following error when trying to set the product -> user association by using: product.setProductManager(user);

Error: Unhandled rejection SequelizeDatabaseError: column "ProductManagerId" of relation "Products" does not exist.

Could someone please tell me where I am going wrong?

Product.js:

'use strict';
/* Model ONLY for DePuy Products */
module.exports = function(sequelize, DataTypes) {
  var Product = sequelize.define('Product', {
    name: {
      type: DataTypes.STRING,
      allowNull : false
    },
    sku: {
      type:DataTypes.STRING,
      allowNull: false,
      primaryKey: true,
    },
  }, {
    classMethods: {
      associate: function(models) {
        Product.belongsTo(models.User,{ as : 'ProductManager'});
        Product.hasMany(models.CompetitorProduct);
        // associations can be defined here
      }
    }
  });
  return Product;
};

User.js

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false,
    },
    username: {
      type: DataTypes.STRING,
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  }, {
    hooks: {
    },
    classMethods: {
      associate: (models) => {
        // associations can be defined here
        User.hasMany(models.Product);
      },
    },
    freezeTableName: true
    }
  });

  return User;
};



via Turtle

No comments:

Post a Comment