Sequelize:如何删除用户相关文章?
P粉212971745
P粉212971745 2024-02-25 17:24:16
0
1
395

我有一个文章模型,其中每篇文章都与一个用户相关:

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,我有点迷失在人际关系中

P粉212971745
P粉212971745

全部回复(1)
P粉523335026

您的文章模型与用户没有任何关系,因为我看到它只有一个用户名。您可以为作者创建一个新集合,当您创建新文章时,将作者 _id 保存在 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);
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!