Sequelize include throws не связанная ошибка - PullRequest
0 голосов
/ 21 апреля 2019

У меня есть таблица Person, таблица Ingredient и таблица PersonIngredient.person и ingredient связаны друг с другом через person_ingredient.Когда я запрашиваю person_ingredient и пытаюсь включить ingredient, я получаю "ingredient is not associated to person_ingredient!"

Почему сиквелиз не позволяет мне присоединиться?

Персональная ассоциация:

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

Ассоциация ингредиентов:

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

определение person_ingredient:

'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;
};

Запрос:

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

Должно привести к

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