Sequelize.js 쿼리를 삭제 하시겠습니까?


99

findAll과 같은 delete / deleteAll 쿼리를 작성하는 방법이 있습니까?

예를 들어 다음과 같이하고 싶습니다 (MyModel이 Sequelize 모델이라고 가정합니다 ...).

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

답변:


236

Sequelize 버전 3 이상을 사용하는 사람은 다음을 사용하십시오.

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

Sequelize 문서 - Sequelize 자습서


내 생각 Sequelize이 의외로 파괴 할 방법이 없었다 당시 있도록 꽤 오래된 질문
ncksllvn

3
그럴 수 있지; 이것이 Google의 첫 번째 검색 결과이기 때문에 사람들은 이미 질문 한 질문을하지 않는 것이 좋습니다. 수락 된 답변이 업데이트되어야하는 것처럼 보이지만 이는 아마도 사이트 전체의 문제 일 것입니다.
Rojuinex

1
나는 sequelize 문서가 제공하지 않는지 궁금합니다. 꽤 쉬운 코딩 샘플 ... 누구나 이것을 이해할 수 있습니다. 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

3
내가처럼 경우 다른 사람에, sequelizejs.com에 대한 설명서에없는) (파괴하는 것은 여기에 찾고 있었다
mikermcneil

2
귀하의 링크는 모두 나를 위해 404를 반환합니다. 제가 유일한가요?
OrwellHindenberg 2016-06-23

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

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이 아니어야합니까?
saraf

1
이것은 더 이상 그렇게 작동하지 않습니다. 반환 값은 영향을받은 행 ID / 영향을받은 행 수가 아닙니다.
Tony Butler

콜백 대신 catch를 사용하여 오류를 잡아야하지 않습니까?
Ahmed Ghrib

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

    }

내가 사용하고 있습니다 !!부울로 결과를 변경됩니다 AWAIT의 결과에 뱅 뱅 운영자.


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,
})
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.