質問

Findallのような削除/Deleteallクエリを書く方法はありますか?

たとえば、私はこのようなことをしたいです(MyModelが後期モデルであると仮定します...):

MyModel.deleteAll({ where: ['some_field != ?', something] })
    .on('success', function() { /* ... */ });
役に立ちましたか?

解決

後遺症バージョン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
    }
  })
})

質問がまだ関連しているかどうかはわかりませんが、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

それが役に立てば幸い!

この例は、コールバックの代わりに約束する方法を示しています。

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

私はしばらく前に帆のためにこのようなことを書きました。

使用例:

// 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.

それが役立つことを願っています!

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

    }

私が使用していることに注意してください !! 待機の結果に関するバンバンオペレーターは、結果をブール値に変更します。

  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));
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top