'how to apply delete in the many to many relation in sequalize
These are the three models.
export const UserPost = sequelize.define(
"user_post",
{
id: {
type: DataTypes.INTEGER,
field: "id",
autoIncrement: true,
primaryKey: true,
},
userId: {
type: DataTypes.INTEGER,
field: "user_id",
},
postId: {
field: "post_id",
type: DataTypes.INTEGER,
},
},
{
freezeTableName: true,
timestamps: true,
createdAt: "created_on",
updatedAt: "updated_on",
}
);
User.belongsToMany(Post, {
through: UserPost,
foreignKey: "userId",
});
Post.belongsToMany(user, {
through: UserPost,
foreignKey: "postId",
});
export default UserPost;
User
export const User = sequelize.define(
"user_post",
{
userId: {
type: DataTypes.INTEGER,
field: "user_id",
autoIncrement: true,
primaryKey: true,
},
},
{
freezeTableName: true,
timestamps: true,
createdAt: "created_on",
updatedAt: "updated_on",
}
);
export default User;
Post
export const Post = sequelize.define(
"user_post",
{
postId: {
type: DataTypes.INTEGER,
field: "post_id",
autoIncrement: true,
primaryKey: true,
},
},
{
freezeTableName: true,
timestamps: true,
createdAt: "created_on",
updatedAt: "updated_on",
}
);
export default Post;
I have two record in the table User with the Id 1 ,3 I have one record in the table Post with the Id 2
I have two record in the table userPost but when I try to delete the record from the table User with the Id 1 and it delete the both two record from the userPost table.
usePost 1 2 3 2
the delete query that I used to delete the records from the table.
const res = await User.destroy({
where: { userId },
cascade: true,
truncate: false,
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
