在 Sequelize 模型钩子函数中访问其他模型
Accessing other models in a Sequelize model hook function
我正在尝试创建一个模型挂钩,它会在创建主模型时自动创建关联记录。当我的模型文件结构如下时,如何在挂钩函数中访问我的其他模型?
/**
* 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;
};
您可以使用 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;
};
您可以通过sequelize.models.OtherModel
访问其他模型。
我正在尝试创建一个模型挂钩,它会在创建主模型时自动创建关联记录。当我的模型文件结构如下时,如何在挂钩函数中访问我的其他模型?
/**
* 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;
};
您可以使用 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;
};
您可以通过sequelize.models.OtherModel
访问其他模型。