Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

327
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda