Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

323
Vistas
Why does Sequelize is inverting the INSERT query it produces by calling the custom N:N method?

Good evening.

I have a database with the following N:N association:

-> BlogPost.belogsToMany(Category through: PostsCategories)

-> Category.belongsToMany(BlogPost through: PostsCategories)

PostsCategories being the junction table's model.

On the process of inserting one BlogPost to the database, I have to catalog in which categories does it fall under on the junction table. So following some examples on the documentation I came up with:

const blogPost = await BlogPost.create({ title, content, userId });
await blogPost.addCategories(categoriesList);

So far so good, but there was an error. Basically Sequelize is inverting the order on the columns/values when writing the query. If I add

blogPost: { id: 3, categories: [1, 2] }

it produces this query:

"'INSERT INTO `PostsCategories` (`categoryId`,`postId`) VALUES (3,1),(3,2);'"

It's inverted and I've tried a gazillion things and it doesn't work. :(

Any thoughts on this?

Thanks!

EDIT: MY MODELS

module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define('Category', {
    name: DataTypes.STRING,
  },
  { tableName: 'Categories', timestamps: false });

  Category.associate = (models) => {
    const { BlogPost, PostsCategories } = models;

    Category.belongsToMany(
      BlogPost, { through: PostsCategories, foreignKey: 'postId', as: 'blogPosts' },
    );
  };

  return Category;
};

module.exports = (sequelize, DataTypes) => {
  const BlogPost = sequelize.define('BlogPost', {
    title: DataTypes.STRING,
    content: DataTypes.STRING,
    userId: DataTypes.INTEGER,
  },
  { tableName: 'BlogPosts', timestamps: true, createdAt: 'published', updatedAt: 'updated' });

  BlogPost.associate = (models) => {
    const { User, PostsCategories, Category } = models;

    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

    BlogPost.belongsTo(User, { foreignKey: 'userId', as: 'user' });
  };

  return BlogPost;
};

module.exports = (sequelize, _DataTypes) => {
  const PostsCategories = sequelize.define('PostsCategories', 
  {},
  { timestamps: false, tableName: 'PostsCategories' });

  return PostsCategories;
};
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I got my answer. Lol.

My association declarations were faulty.

    BlogPost.belongsToMany(
      Category, { through: PostsCategories, foreignKey: 'categoryId', as: 'categories' },
    );

Actually the foreignKey is related to the BlogPost on the junction table.

I also inverted my declaration to being able to "read" it better.

    BlogPost.belongsToMany(
      Category, { as: 'categories', through: PostsCategories, foreignKey: 'postId' },
    );

BlogPost belongsToMany Category

  • if I query a BlogPost and want it with every category it'll return as 'categories'
  • the association is established through PostsCategories
  • the way the BlogPost associate with PostsCategories is with the foreignKey 'postId'
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda