Sequelize.js删除查询?


99

有没有一种方法可以编写类似于findAll的delete / deleteAll查询?

例如,我想做这样的事情(假设MyModel是一个Sequelize模型...):

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

Answers:


236

对于使用Sequelize 3及更高版本的任何人,请使用:

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

Sequelize文档 - Sequelize教程


这是一个很老的问题,所以当时我想Sequelize并没有令人惊讶的销毁方法
ncksllvn

3
很公平; 尽管因为这是Google上的第一个搜索结果,并且人们也不想提出已经提出的问题,所以似乎应该更新已接受的答案……但这可能更多是站点范围的问题。
Rojuinex

1
我想知道续集文档没有给出,这么简单的编码示例……任何人都可以理解。谢谢ncksllvn。您节省了我的时间...
weeraa

如果ID为无效ID,该如何处理?
Rod

21

我已对代码进行了深入搜索,并逐步查找了以下文件:

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

是的,我知道销毁方法,但不幸的是,它仅用于一项记录。我猜我将不得不编写自己的deleteAll方法。谢谢!
lakenen 2011年

真奇怪,这不存在。也许您可以自己编写它并提交拉取请求以进行续集。我确信其他人真的可以使用它。
alessioalex 2011年

1
随时提交拉取请求或在github存储库中打开问题:)
sdepold 2011年

3
sequelizejs.com上的文档中没有destroy(),以防万一有人在这里寻找像我一样的东西
mikermcneil 2012年

2
您的链接都为我返回了404。我是唯一一个?
OrwellHindenberg

16

不知道该问题是否仍然相关,但是我在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

希望能帮助到你!


2
作为参考,这是在lib / model.js中定义的,您不必使用字符串。您可以使用任何类型的where对象(例如{someId: 123})。
Domi 2014年

10

这个例子展示了如何承诺而不是回调。

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


1
检查成功删除一行时,rowDeleted不应该为1吗?
萨拉夫

1
这不再像那样工作。返回值是受影响的行ID /不是受影响的行数。
托尼·巴特勒

您不应该使用catch来捕获错误而不是回调吗?
艾哈迈德·格里布

7

在新版本中,您可以尝试这样的操作

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

4

这是一个使用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运算符,它将把结果更改为布尔值。


2

我为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

希望有帮助!


0
  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));

0

全部删除,无条件:

Model.destroy({
    truncate: true,
})
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.