首頁  >  問答  >  主體

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粉212971745236 天前382

全部回覆(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 })
           // 其中: { 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
  • 取消回覆