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