Hey there!
I am currently working with a database that has an N:N association setup as follows:
-> BlogPost belongs to many Categories through PostsCategories
-> Category belongs to many BlogPosts through PostsCategories
The model for the junction table is called PostsCategories.
When inserting a BlogPost into the database, it is important to categorize it under the relevant categories in the junction table. While following some documentation examples, I tried the following code snippet:
const blogPost = await BlogPost.create({ title, content, userId });
await blogPost.addCategories(categoriesList);
Everything seemed fine until I encountered an error. It appears that Sequelize is flipping the order of columns/values when executing the query. For instance, when I use
blogPost: { id: 3, categories: [1, 2] }
it generates this inverted query:
"'INSERT INTO `PostsCategories` (`categoryId`,`postId`) VALUES (3,1),(3,2);'"
I have tried multiple solutions but haven't been successful. :(
Any suggestions on how to resolve this issue?
Thank you!
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;
};