当用户两次单击“赞”按钮时,我无法删除赞。用户具有喜欢帖子的能力,再次单击它时,我需要相同的功能。我假设onDelete
将使这成为可能。
我在喜欢的模型上配置了onDelete
module.exports = function(sequelize, DataTypes) {
const Like = sequelize.define('Likes', {
like:{
type:DataTypes.BOOLEAN,
allowNull:true
},
}, {});
Like.associate = function(models) {
// foreign key will attach a userId to the likes table
Like.belongsTo(models.User, {
onDelete: 'CASCADE',
foreignKey: 'userId',
targetKey: 'id'
})
Like.belongsTo(models.Post, {
onDelete: 'CASCADE',
foreignKey: 'postId',
targetKey: 'id'
})
}
return Like;
}
发布模型
module.exports = (sequelize, DataTypes) => {
const Post = sequelize.define('Post', {
title: DataTypes.STRING,
post_content: DataTypes.STRING,
username: DataTypes.STRING
}, {});
Post.associate = function(models) {
Post.belongsTo(models.User, { foreignKey: 'userId', targetKey: 'id' });
// foreign key id will attach a postId to the likes table.
Post.hasMany(models.Likes, { foreignKey: 'postId', targetKey: 'id', onDelete: 'CASCADE' });
};
return Post;
};
routes / posts.js
router.post('/like', (req, res)=> {
models.Likes.create({
postId: req.body.postId,
userId: req.user.id,
like:true
}).then( () => {
res.status(200).send({
message: 'You have like this post',
});
}).catch( (err) => {
res.status(401).send({
message: "Something went wrong",
err: err
})
})
})