Heim  >  Fragen und Antworten  >  Hauptteil

Sequelize: Wie lösche ich benutzerbezogene Artikel?

Ich habe ein Artikelmodell, bei dem sich jeder Artikel auf einen Benutzer bezieht:

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;

Wie lösche ich alle von einem Benutzer erstellten Artikel, wenn er sein Konto löscht?

Ich habe die folgende Funktion, um einen Benutzer zu löschen:

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!" });
    }
}

Ich bin von Mongodb zu MySQL gewechselt und bin ein bisschen verloren in Beziehungen

P粉212971745P粉212971745237 Tage vor389

Antworte allen(1)Ich werde antworten

  • 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);
        }
    }

    Antwort
    0
  • StornierenAntwort