首页  >  问答  >  正文

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

P粉212971745P粉212971745237 天前388

全部回复(1)我来回复

  • P粉523335026

    P粉5233350262024-02-26 16:27:45

    您的文章模型与用户没有任何关系,因为我看到它只有一个用户名。您可以为作者创建一个新集合,当您创建新文章时,将作者 _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);
        }
    }

    回复
    0
  • 取消回复