Sequelize.js ลบแบบสอบถาม?


101

มีวิธีเขียนข้อความค้นหา delete / deleteAll เช่น findAll หรือไม่?

ตัวอย่างเช่นฉันต้องการทำสิ่งนี้ (สมมติว่า MyModel เป็นโมเดล Sequelize ... ):

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

คำตอบ:


248

สำหรับใครก็ตามที่ใช้ Sequelize เวอร์ชัน 3 ขึ้นไปให้ใช้:

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

Sequelize Documentation - Sequelize Tutorial


เป็นคำถามที่ค่อนข้างเก่าในตอนนั้นฉันเดาว่า Sequelize ไม่มีวิธีการทำลายที่น่าแปลกใจ
ncksllvn

3
พอใช้; แม้ว่าเนื่องจากนี่เป็นผลการค้นหาแรกใน Google และผู้คนก็ไม่แนะนำให้ถามคำถามที่ถามไปแล้วดูเหมือนว่าคำตอบที่ได้รับการยอมรับควรได้รับการอัปเดต ... แต่นั่นอาจเป็นปัญหาทั่วทั้งไซต์
Rojuinex

1
ฉันสงสัยว่าเอกสารต่อเนื่องไม่ได้ให้ตัวอย่างการเข้ารหัสที่ค่อนข้างง่ายนี้ ... ใคร ๆ ก็เข้าใจสิ่งนี้ ขอบคุณ ncksllvn. คุณช่วยฉัน ...
weeraa

คุณจะจัดการอย่างไรหากรหัสนั้นเป็นรหัสที่ไม่ถูกต้อง?
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
    }
  })
})

ใช่ฉันรู้เกี่ยวกับวิธีการทำลาย แต่น่าเสียดายที่มันเป็นเพียงบันทึกเดียว ฉันเดาว่าฉันจะต้องเขียนวิธีการลบทั้งหมดของฉันเอง ขอบคุณ!
lakenen

แปลกจริงๆที่ไม่มีสิ่งนี้ บางทีคุณอาจเขียนเองและส่งคำขอดึงเพื่อสร้างภาคต่อได้ ฉันแน่ใจว่าคนอื่นสามารถใช้มันได้จริงๆ
alessioalex

1
อย่าลังเลที่จะส่งคำขอดึงหรือเปิดปัญหาในที่เก็บ github :)
sdepold

3
destroy () ไม่ได้อยู่ในเอกสารของ sequelizejs.com ในกรณีที่มีใครอยู่ที่นี่กำลังมองหาสิ่งนั้นเหมือนฉัน
mikermcneil

2
ลิงก์ของคุณส่งคืน 404 ให้ฉันทั้งหมด ฉันเป็นคนเดียวเหรอ?
ออร์เวลล์ฮินเดนเบิร์ก

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

11

ตัวอย่างนี้แสดงให้เห็นว่าคุณสัญญาอย่างไรแทนที่จะโทรกลับ

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 เมื่อตรวจสอบการลบหนึ่งแถวสำเร็จหรือไม่
saraf

1
วิธีนี้ใช้ไม่ได้อีกต่อไป Return คือ ID แถวที่ได้รับผลกระทบ / ไม่ใช่จำนวนแถวที่ได้รับผลกระทบ
Tony Butler

คุณไม่ควรใช้ catch เพื่อตรวจจับข้อผิดพลาดแทนการโทรกลับใช่หรือไม่?
Ahmed Ghrib

8

ในเวอร์ชันใหม่คุณสามารถลองสิ่งนี้ได้

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

5

นี่คือ ES6 โดยใช้ตัวอย่าง Await / Async:

    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 Operator กับผลลัพธ์ของการรอคอยซึ่งจะเปลี่ยนผลลัพธ์เป็นบูลีน


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

หวังว่าจะช่วยได้!


1

ฉันใช้ 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);
    });
}

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

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.