Js 删除查询?

有没有像 findAll 那样编写 delete/delete teAll 查询的方法?

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

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

我已经深入地搜索了代码,一步一步地查看以下文件:

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

我发现:

这里没有 delete teAll 方法,但是有一个 delete ()方法可以对记录进行调用,例如:

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

不久前我为 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 的文档中找到了以下内容。

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

希望能有帮助!

对于使用 Sequelize 版本3及以上版本的用户,请使用:

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

Sequelize Documents -< a href = “ http://docs.Sequelizejs.com/hand/lessons/instances.html # working-in-mass-create-update-and- 毁掉多行-at-once-”rel = “ norefrer”> Sequelize Tutorial

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

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 操作符来处理等待的结果,这将把结果变成一个布尔值。

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

我在下面的代码中使用了 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 方法返回承诺,并且没有 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

使用 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: {} })
        

简单的删除查询 删除查询也接受 where 选项,就像上面显示的 read 查询一样。

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

要摧毁所有 TRUNCATE SQL 可以使用的东西:

// Truncate the table
await User.destroy({
truncate: true
});