[英]how to delete user related article in sequelize?
我有一个文章模型,其中每篇文章都与用户相关:
const Articles = db.define("Articles", { title: { type: DataTypes.STRING, allowNull: false, }, description: { type: DataTypes.STRING, allowNull: false, }, img_url: { type: DataTypes.STRING, allowNull: false, }, author: { type: DataTypes.STRING, allowNull: false, }, }); Articles.belongsTo(User); module.exports = Articles;
用户删除账号时,如何删除用户创建的所有文章?
我有以下功能来删除用户:
static async deleteUserById(req, res) { const id = req.params.id; const user = await User.findOne({ where: { id: id, }, }); if (!user) { res.status(404).json({ msg: "User not found!" }); return; } try { await User.destroy({ where: { id: id, }, }); res.status(200).json({ msg: "Account successfully deleted!" }); } catch (msg) { res.status(500).json({ msg: "Oops... an error has occurred!" }); } }
我从 mongodb 到 mysql,我有点迷失在人际关系中
您的 Article 模型与 User 没有任何关系,因为我看到它只有一个用户名。 您可以为 Author 创建一个新集合,当您创建新文章时,将 Author _id
保存在author
字段中就可以了。
现在,当您删除用户时,您可以根据 Author 键查询文章集合并将其删除。 但是,一旦删除,您将无法取回这些文章。
static async deleteUserById(req, res) {
const id = req.params.id;
try {
const user = await User.remove({ // O/p WriteResult({ "nRemoved" : 1 })
// where: { no need of where clause
// id: id,
//},
"_id": id
});
// once you remove the user
// remove articles
const articles = await Articles.remove({ 'author': 'pass_author_id' });
// do your things
} catch(e) {
console.log(error);
}
}
我设法通过从文章模型中添加以下代码来解决它:
User.hasMany(Article, {
onDelete: "CASCADE",
});
我的错误是我试图在用户模型中使用这个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.