I have a Person table, Ingredient table, and a PersonIngredient table. person and ingredient are associated to each other through person_ingredient. When I query person_ingredient and try to include ingredient I get "ingredient is not associated to person_ingredient!"

Why is sequelize not allowing me to do this join?

Person Association:

person.associate = function(models) {
  // associations can be defined here
  person.belongsToMany(models.ingredient, {through: {model: models.person_ingredient, unique: false}});
};

Ingredient Association:

ingredient.associate = function(models) {
  ingredient.belongsToMany(models.person, {through: {model: models.person_ingredient, unique: false}});
};

person_ingredient definition:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const person_ingredient = sequelize.define('person_ingredient', {
    id: {
      type: DataTypes.BIGINT,
      primaryKey: true, 
      autoIncrement: true,
      allowNull: false
    },
    person_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      references: {
        model: 'person',
        key: 'id'
      },
      onUpdate: 'cascade',
      onDelete: 'cascade'
    },
    ingredient_id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      references: {
        model: 'ingredient',
        key: 'id'
      },
      onUpdate: 'cascade',
      onDelete: 'cascade'
    },
    archived: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    custom_ingredient: {
      type: DataTypes.TEXT
    }
  }, {
    underscored: true,
    freezeTableName: true
  });
  person_ingredient.associate = function(models) {
    // associations can be defined here
  };
  return person_ingredient;
};

Query:

let person = await db.Person.findOne({where:{email : email}});
let personIngredients = await db.PersonIngredient.findAll({
    include: [
        db.Ingredient
    ],
    where:{person_id: person.id}
});

Should result to

SELECT person_ingredient.*, ingredient.*
FROM person_ingredient
JOIN ingredient ON ingredient.id = person_ingredient.ingredient_id
WHERE person_ingredient.person_id = 'id'

0 Answers