如何访问将在'before delete'操作钩子中删除的模态实例?



before saveafter save操作挂钩具有datainstance属性,其中包含将要更改的部分数据或模型实例。请参见此处。如何访问before delete挂钩中的模型实例?

手头的案例:我想在删除特定模型时删除相关项目。

我也使用before delete观察器实现了这一点。

在本例中,有一个Category模型,它与许多通过categoryId属性相关的产品有关系。

它首先根据categoryId搜索所有匹配的产品,然后在结果集products上循环以逐个删除它们。

module.exports = function (Category) {
Category.observe('before delete', function (ctx, next) {
    // It would be nice if there was a more elegant way to load this related model
    var Product = ctx.Model.app.models.Product;
    Product.find({
      where: {
        categoryId: ctx.where.id
      }
    }, function (err, products) {
      products.forEach(function (product) {
        Product.destroyById(product.id, function () {
          console.log("Deleted product", product.id);
        });
      });
    });
    next();
  });
};

我曾尝试使用destroyAll方法来实现它,但没有得到预期的结果。

上面的代码对我来说是有效的,但看起来它可以增强很多。

下面是jakerella代码的修改版本,使用findById,计数和删除相关项目(在"hasMany"关系中,命名为"relatedItems"):

MyModel.observe('before delete', function(context, next) {
    console.log('About to delete some: ' + context.Model.pluralModelName);
    console.log('using the WHERE clause: ' + context.where);
    MyModel.findById(context.where.id, function(err, model) {
        console.log('found model:', model);
        model.relatedItems.count(function(err, count) {
            console.log('found ', count, ' related items');
        });
        model.relatedItems.destroyAll(function(err) {
            if (err) {
                console.log('found ', count, ' related items');
           }
        });
        next();   
   });
});

我不认为您实际上可以访问要删除的特定实例,但您可以访问调用的上下文对象,该对象包括一个where属性,该属性标识将选择进行删除的实例:

MyModel.observe('before delete', function(context, next) {
  console.log('About to delete some: ' + context.Model.pluralModelName);
  console.log('using the WHERE clause: ' + context.where);
  MyModel.find({ where: context.where }, function(err, models) {
    console.log('found some models:', models);
    // loop through models and delete other things maybe?
  });
  next();
});

这在文档中,但没有很好地解释。您可以使用contect.Model对象来获取一个实例,然后您可以访问相关模型并删除它们。

在所有挂钩中(之前或之后)始终可以访问"this"。在销毁之前,modelhook"this"对象将包含环回要销毁的modelInstances。

最新更新