如何在Sequelize M:M关联上触发“ afterDestroy”生命周期挂钩?

时间:2019-04-22 21:19:39

标签: mysql node.js orm sequelize.js

我正在使用Sequelize ORM在Web应用程序中设置一些模型定义。如何在联接(通过)表的模型上触发afterDestroyafterBulkDestroy生命周期挂钩?使用以下上下文将联接表称为foo_bar

我尝试将hooks: trueonDelete: 'cascade'添加到我的协会的选项中,没有任何运气。像这样:

Foo.belongsToMany(
 models.bar,
 {
   through: 'foo_bar',
   foreignKey: 'foo_id',
   onDelete: 'cascade',
   hooks: true
 }

Bar.belongsToMany(
 models.foo,
 {
   through: 'foo_bar',
   foreignKey: 'bar_id',
   onDelete: 'cascade',
   hooks: true
 }

下面是我尝试调用afterDestroyafterBulkDestroy生命周期挂钩的过程。

// controller
module.exports = (req, res, next) => {

    const { id } = req.query;

    models.foo.destroy({ where: { id } })
               .then(() => res.json({ success: true }))
               .catch(err => res.json({ success: false, error: err }))
}
// foo_bar model definition
module.exports = (sequelize, DataTypes) => {
  var foo_bar = sequelize.define('foo_bar', {}, {
    hooks: {
      afterBulkDestroy: (instances, options) => {
        console.log('foo_bar::afterBulkDestroy()');
      },
      afterDestroy: (instance, options) => {
        console.log('foo_bar::afterDestroy()');
      }
    }
  })

 return foo_bar;
};

0 个答案:

没有答案