续集 - 在具有 onDelete 级联的实例上调用 beforeDestroy 挂钩



我有一个涉及两个表(一对多(的方案,用户可以从第一个表(名称:文档,关系:一个(中删除记录或记录数组,然后从我的第二个表(名称:文件,关系:多(中删除与该表关联的记录。"文件"表上的onDelete级联正在正常工作,但我的钩子从未触发。

  • 我需要在我的.destroy中的某个地方调用钩子才能续集吗 方法?
  • 因为我的关系是一对多,一个用户可以有多个 文件或一个文档的单个文件,我需要为 beforeDestroybeforeBulkDestroy

下面是两个表之间的关联:

公文

var Document = sequelize.define('document', {
    ...
},
{
    underscored: true,
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Document.hasMany(db.File, { foreignKey: 'document_id'}),
        }
    }
});
return Document;

文件

var File = sequelize.define('file', {
    ...
},{
    underscored: true,
    freezeTableName: true,
    hooks: {
        beforeDestroy: function(whereClause, fn){
            //options.individualHooks = true;
            console.log('whereClause Start');
            console.log(whereClause);
            console.log('fn start');
            console.log(fn);
        },
        beforeBulkDestroy: function(whereClause, fn) {
            //options.individualHooks = true;
            console.log('whereClause Start');
            console.log(whereClause);
            console.log('fn start');
            console.log(fn);   
        }
    },
    classMethods: {
        associate: function(db) {
            File.belongsTo(db.Document, { onDelete: 'CASCADE', hooks: true});
        }
    }
});
return File;

仅续集触发器方案:

models.Document.destroy({
    where: {
        userId: req.user.userId,
        documentId: documentId //Replace with array in certain instances
    }
});

我遇到了同样的问题。因为文档 (v5(:

注意:您不能对实例使用挂钩。钩子与模型一起使用。

实例挂钩:每当编辑单个对象时,都会发出以下挂钩

给出非常复杂的视图,我决定不按实例models.Document.destroy(where)销毁,而是按模型销毁(选择模型,然后document.destroy()(。这样做时会发射钩子。

似乎 Sequelize (v5( 只是在您现在使用 cascades 时无法调用钩子。

默认情况下,Model.destroy() 方法不会调用 beforeDestroy 钩子。您可以使用individualHooks: true选项强制它这样做,如下所示

models.Document.destroy({
    where: {
        userId: req.user.userId,
        documentId: documentId //Replace with array in certain instances
    },
    individualHooks: true
})

看:

https://github.com/sequelize/sequelize/issues/10270

https://sequelize.org/master/manual/hooks.html#model-hooks

如果你愿意,你也可以在这个模型上对任何批量破坏进行吉米装备,以始终发射单个钩子。这可以通过beforeBulkDestroy钩子来完成:

    beforeBulkDestroy: async (options) =>
        (options.individualHooks = true),

但当然,这可能是密集的,可能不是期望的行为。

最新更新