0
votes

I have a database that was originally created with Django that was setup for a single foreign key association, here is the JSON dump.

Now this would be mapped as:

export const Category = sequelize.define(
  'category',
  {
    name: { type: Sequelize.STRING, unique: true },
  },
  {
    timestamps: false,
    tableName: 'ingredients_category',
  }
);

export const Ingredient = sequelize.define(
  'ingredient',
  {
    name: { type: Sequelize.STRING, unique: true },
    notes: { type: Sequelize.TEXT, defaultValue: '' },
    category_id: {
      type: Sequelize.INTEGER,
      references: {
        model: Category,
        key: 'id',
      },
    },
  },
  {
    timestamps: false,
    tableName: 'ingredients_ingredient',
  }
);

Category.belongsToMany(Ingredient, {
  foreignKey: 'category_id',
  constraints: false,
  through: 'ingredient_category',
});
Ingredient.hasOne(Category, {
  // foreignKey: 'ingredientId',
  constraints: false,
});

Now sequelize complains that it is missing a foreign key on the Category model, but while there is only a single category on an ingredient the categories are not restricted to that one ingredient. Can someone help me to make sense of this association?

UPDATE: For the final answer it was just an incorrect association setup:

export const Category = sequelize.define(
  'category',
  {
    name: { type: Sequelize.STRING, unique: true },
  },
  {
    timestamps: false,
    tableName: 'ingredients_category',
  }
);

export const Ingredient = sequelize.define(
  'ingredient',
  {
    name: { type: Sequelize.STRING, unique: true },
    notes: { type: Sequelize.TEXT, defaultValue: '' },
  },
  {
    timestamps: false,
    tableName: 'ingredients_ingredient',
  }
);

Category.hasMany(Ingredient, {
  foreignKey: 'category_id',
});
Ingredient.belongsTo(Category, {
  foreignKey: 'category_id',
});
1

1 Answers

2
votes

belongsToMany is used on a relationship N:M so ingredient_category should be a third table. Now as I understand you need a relationship where ingredients 1:N categories, so a Category can have many ingredients, so you should use hasMany.

On your case you can't use hasOne because it creates the foreign key of ingredients on Categories, and hasMany will create the FK on ingredients.

Category.hasMany(Ingredient, {
  foreignKey: 'category_id',
  constraints: false,
});
Ingredient.belongsTo(Category, {
  // foreignKey: 'ingredientId',
  constraints: false,
});

Here is the documentation: