2015-03-28 2 views
5

Sto provando a creare un hook di modello che crea automaticamente un record associato quando il modello principale è stato creato. Come posso accedere agli altri miei modelli all'interno della funzione di hook quando il mio file di modello è strutturato come segue?Accesso ad altri modelli in una funzione di hook Sequelize model

/** 
* Main Model 
*/ 
module.exports = function(sequelize, DataTypes) { 

    var MainModel = sequelize.define('MainModel', { 

    name: { 
     type: DataTypes.STRING, 
    } 

    }, { 

    classMethods: { 
     associate: function(models) { 

     MainModel.hasOne(models.OtherModel, { 
      onDelete: 'cascade', hooks: true 
     }); 

     } 
    }, 

    hooks: { 

     afterCreate: function(mainModel, next) { 
     // ------------------------------------ 
     // How can I get to OtherModel here? 
     // ------------------------------------ 
     } 

    } 

    }); 


    return MainModel; 
}; 

risposta

16

È possibile accedere all'altro modello tramite sequelize.models.OtherModel.

+0

'sequelize' non è disponibile. – user1107173

2

È possibile utilizzare this.associations.OtherModel.target.

/** 
* Main Model 
*/ 
module.exports = function(sequelize, DataTypes) { 

    var MainModel = sequelize.define('MainModel', { 

    name: { 
     type: DataTypes.STRING, 
    } 

    }, { 

    classMethods: { 
     associate: function(models) { 

     MainModel.hasOne(models.OtherModel, { 
      onDelete: 'cascade', hooks: true 
     }); 

     } 
    }, 

    hooks: { 

     afterCreate: function(mainModel, next) { 
     /** 
     * Check It! 
     */ 
     this.associations.OtherModel.target.create({ MainModelId: mainModel.id }) 
     .then(function(otherModel) { return next(null, otherModel); }) 
     .catch(function(err) { return next(null); }); 
     } 

    } 

    }); 


    return MainModel; 
};