programing

sufficize.js 삭제 쿼리?

telebox 2023. 8. 20. 10:44
반응형

sufficize.js 삭제 쿼리?

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

예를 들어, 이와 같은 작업을 수행하고 싶습니다(내 모델이 후속 모델이라고 가정하면...):

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

Sequetize 버전 3 이상을 사용하는 사용자는 다음을 사용합니다.

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

다큐멘터리 후속편 - 후속편 튜토리얼

저는 코드를 자세히 검색했고, 다음 파일들을 단계적으로 검색했습니다.

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

이 예에서는 콜백 대신 약속하는 방법을 보여 줍니다.

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/ #sysoptions-sysinteger

그 질문이 여전히 관련이 있는지는 모르겠지만, 저는 Suquetize의 문서에서 다음과 같은 것을 발견했습니다.

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

도움이 되길 바랍니다!

새로운 버전에서는 다음과 같은 것을 시도할 수 있습니다.

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

다음은 Wait/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 연산자가 결과를 부울로 변경합니다.

얼마 전에 세일스를 위해 이런 글을 썼습니다. 시간을 절약할 수 있을지도 모르니까요.

사용 예:

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

출처: 또는 m.js.

도움이 되길 바랍니다!

저는 sufficialize.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);
    });
}

속편화 방법은 약속을 반환하며, 약속은 없습니다.delete()방법.후속 사용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

단순 삭제 쿼리 삭제 쿼리는 위에 표시된 읽기 쿼리와 마찬가지로 where 옵션도 사용할 수 있습니다.

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

TRUNCATE SQL을 사용할 수 있는 모든 항목을 삭제하려면 다음을 수행합니다.

// Truncate the table
await User.destroy({
  truncate: true
});
  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: {} })
        

언급URL : https://stackoverflow.com/questions/8402597/sequelize-js-delete-query

반응형