简体   繁体   中英

How can I instantiate a model in Lifecycle callbacks in sails?

How can I instantiate a model in Lifecycle callbacks different than this? After I delete a record on the parent model I want to delete those associated records of the son model in afterDestroy. For example:

/**
 * Survey.js
 *
 */

  attributes: {
    question: {
      type: 'string',
      required: true
    },
    active: {
      type: 'boolean'
    },

    // Below is all specification for relations to another models
    answers: {
      collection: 'answer',
      via: 'answer'
    }
  },

  // Lifecycle Callbacks
  afterDestroy: function (destroyedRecords, cb) {
    answer.destroy({survey: destroyedRecords[0].id}).exec(function(err, answers) {
      console.log(answers);
    });
    cb();
  }
});

With this I received an error that 'answer' is not defined

Solved. To instantiate a model in Lifecycle callbacks in Sails different than 'this' you need you need to precede the model with sails.models. For the previous code:

  // Lifecycle Callbacks
  afterDestroy: function (destroyedRecords, cb) {
    sails.models.answer.destroy({survey: destroyedRecords[0].id}).exec(function(err, answers) {
      console.log(answers);
    });
    cb();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM