set*_*ter 10 node.js sequelize.js
我正在尝试创建一个模型挂钩,在创建主模型时自动创建关联记录.当我的模型文件结构如下时,如何在钩子函数中访问我的其他模型?
/**
* 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;
};
Run Code Online (Sandbox Code Playgroud)
Jac*_*358 30
您可以通过访问其他模型sequelize.models.OtherModel.
您可以使用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;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5257 次 |
| 最近记录: |