Lisandro Dalla Costa
Lisandro Dalla Costa

Reputation: 131

Sequelize "include" not working white many-to-many relations

I'm new to Node and Sequelize, and i'm building a basic eCommerce. These are my models:

const Product = sequelize.define('product', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
});

const Sale = sequelize.define('sale', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  isDelivered: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    allowNull: false,
  },
});

And these the relations:

Sale.belongsToMany(Product, { through: SaleItem });
Product.belongsToMany(Sale, { through: SaleItem });

The problem starts when I try to get the "SaleItems"

 SaleItem.findAll({
    include: [Product],
  })
  .then(response => {
   console.log(response);
  })

I get the response:

SequelizeEagerLoadingError: product is not associated to saleItem!

It's strange, couse I'm doing the same on a one-to-many relation, and works perfectly.

Thanks for your time :)

Upvotes: 0

Views: 147

Answers (1)

Anatoly
Anatoly

Reputation: 22758

You have associations between Product and Sale but not between them and SaleItem.

Your existing associations let you execute only queries like this:

Sale.findAll({
    include: [Product],
  })
  .then(response => {
   console.log(response);
  })
Product.findAll({
    include: [Sale],
  })
  .then(response => {
   console.log(response);
  })

You need to add associations for SaleItem like this:

SaleItem.belongsTo(Product);
SaleItem.belongsTo(Sale);

in order to get SaleItem records along with associated model instances.

Upvotes: 1

Related Questions