簡體   English   中英

"Sequelize.js 刪除查詢?"

[英]Sequelize.js delete query?

有沒有辦法像 findAll 一樣編寫 delete\/deleteAll 查詢?

例如,我想做這樣的事情(假設 MyModel 是 Sequelize 模型......):

MyModel.deleteAll({ where: ['some_field != ?', something] })
    .on('success', function() { /* ... */ });

對於使用 Sequelize 3 及以上版本的任何人,請使用:

Model.destroy({
    where: {
        // criteria
    }
})

Sequelize 文檔- Sequelize 教程

我已經深入搜索了代碼,一步一步進入了以下文件:

https://github.com/sdepold/sequelize/blob/master/test/Model/destroy.js

https://github.com/sdepold/sequelize/blob/master/lib/model.js#L140

https://github.com/sdepold/sequelize/blob/master/lib/query-interface.js#L207-217

https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js

我發現了什么:

沒有 deleteAll 方法,有一個可以在記錄上調用的 destroy() 方法,例如:

Project.find(123).on('success', function(project) {
  project.destroy().on('success', function(u) {
    if (u && u.deletedAt) {
      // successfully deleted the project
    }
  })
})

不知道這個問題是否仍然相關,但我在 Sequelize 的文檔中找到了以下內容。

User.destroy('`name` LIKE "J%"').success(function() {
    // We just deleted all rows that have a name starting with "J"
})

http://sequelizejs.com/blog/state-of-v1-7-0

希望能幫助到你!

這個例子展示了如何向你承諾而不是回調。

Model.destroy({
   where: {
      id: 123 //this will be your id that you want to delete
   }
}).then(function(rowDeleted){ // rowDeleted will return number of rows deleted
  if(rowDeleted === 1){
     console.log('Deleted successfully');
   }
}, function(err){
    console.log(err); 
});

查看此鏈接以獲取更多信息http://docs.sequelizejs.com/en/latest/api/model/#destroyoptions-promiseinteger

在新版本中,您可以嘗試這樣的操作

function (req,res) {    
        model.destroy({
            where: {
                id: req.params.id
            }
        })
        .then(function (deletedRecord) {
            if(deletedRecord === 1){
                res.status(200).json({message:"Deleted successfully"});          
            }
            else
            {
                res.status(404).json({message:"record not found"})
            }
        })
        .catch(function (error){
            res.status(500).json(error);
        });

這是一個使用 Await / Async 的 ES6 示例:

    async deleteProduct(id) {

        if (!id) {
            return {msg: 'No Id specified..', payload: 1};
        }

        try {
            return !!await products.destroy({
                where: {
                    id: id
                }
            });
        } catch (e) {
            return false;
        }

    }

請注意,我正在使用!! 等待結果的 Bang Bang 運算符,它將結果更改為布爾值。

不久前我為 Sails 寫了這樣的東西,以防它為您節省一些時間:

用法示例:

// Delete the user with id=4
User.findAndDelete(4,function(error,result){
  // all done
});

// Delete all users with type === 'suspended'
User.findAndDelete({
  type: 'suspended'
},function(error,result){
  // all done
});

來源:

/**
 * Retrieve models which match `where`, then delete them
 */
function findAndDelete (where,callback) {

    // Handle *where* argument which is specified as an integer
    if (_.isFinite(+where)) {
        where = {
            id: where
        };
    }

    Model.findAll({
        where:where
    }).success(function(collection) {
        if (collection) {
            if (_.isArray(collection)) {
                Model.deleteAll(collection, callback);
            }
            else {
                collection.destroy().
                success(_.unprefix(callback)).
                error(callback);
            }
        }
        else {
            callback(null,collection);
        }
    }).error(callback);
}

/**
 * Delete all `models` using the query chainer
 */
deleteAll: function (models) {
    var chainer = new Sequelize.Utils.QueryChainer();
    _.each(models,function(m,index) {
        chainer.add(m.destroy());
    });
    return chainer.run();
}

來自: orm.js

希望有幫助!

我在下面的代碼中使用了 sequelize.js、node.js 和事務,並添加了正確的錯誤處理,如果它沒有找到數據,它會拋出錯誤,沒有找到具有該 ID 的數據

deleteMyModel: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let feature = await sequelize.MyModel.findOne({
            where: {
                id: req.body.id
            }
        })

        if (feature) {
            let feature = await sequelize.MyModel.destroy({
                where: {
                    id: req.body.id
                }
            });

            let result = error.OK;
            result.data = MyModel;
            return res.status(200).send(result);

        } else {
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        return res.status(500).send(error.SERVER_ERROR);
    });
}

Sequelize 方法返回 promise,並且沒有delete()方法。 Sequelize 使用destroy()代替。

例子

Model.destroy({
  where: {
    some_field: {
      //any selection operation
      // for example [Op.lte]:new Date()
    }
  }
}).then(result => {
  //some operation
}).catch(error => {
  console.log(error)
})

有關更多詳細信息的文檔: https : //www.codota.com/code/javascript/functions/sequelize/Model/destroy

  1. 刪除一條記錄的最好方法是先找到它(如果數據庫中同時存在你想刪除它)
  2. 看這個代碼
const StudentSequelize = require("../models/studientSequelize"); const StudentWork = StudentSequelize.Student; const id = req.params.id; StudentWork.findByPk(id) // here i fetch result by ID sequelize V. 5 .then( resultToDelete=>{ resultToDelete.destroy(id); // when i find the result i deleted it by destroy function }) .then( resultAfterDestroy=>{ console.log("Deleted :",resultAfterDestroy); }) .catch(err=> console.log(err));

全部刪除,無條件:

Model.destroy({
    truncate: true,
})

使用 API 方法的示例

exports.deleteSponsor = async (req, res) => {
  try {

using conditions like userid,eventid and sponsorid

    const { userId } = req.body;
    const { eventId } = req.body;
    const { sponsorId } = req.body;

checking exist or not

    if (!sponsorId)
      return res
        .status(422)
        .send({ message: "Missing Sponsor id in parameters" });
`checking in db too`

    const sponsorDetails = await Sponsor.findAll({
      where: { [Op.or]: [{ id: sponsorId }] },
    });

    if (sponsorDetails.length === 0) {
      return res.status(422).send({ message: "Sponsor id not exist" });
    } else {
      await Sponsor.destroy({

where clause as per your requirements you can change

        where: {
          id: sponsorId,
          userId: userId,
          eventId: eventId,
        }
      });
      return res
        .status(201)
        .send({ message: "Sponsor deleted successfully" });
    }
  } catch (err) {
    console.log(err);
    customGenericException(err, res);
  }
};

您可以使用如下所示刪除所有行。

general_category.destroy({ truncate: true, where: {} })
        

簡單的 DELETE 查詢<\/a>刪除查詢也接受 where 選項,就像上面顯示的讀取查詢一樣。

// Delete everyone named "Jane"
await User.destroy({
  where: {
    firstName: "Jane"
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM