LOOPBACK修改钩子内的另一个模型
当事务模型中的属性“code”等于3时,我想在Event模型中插入新数据
module.exports = function(Transaction) { Transaction.observe('before save', function(ctx, next) { if(ctx.data.code == 3){ //How to access and insert data in Event model ? } }); };
如果您有一个带有插入newData的函数的Event模型。 只要参考模型。 例如:
var eventModel = require('pathtoEventModel'); module.exports = function(Transaction) { Transaction.observe('before save', function(ctx, next) { if(ctx.data.code == 3){ eventModel.saveNewData(ctxBeingNewData,function(response,next){ //manipulate as per your wish. }) }
}); };
这对我有用。 这就像@Sunil喇嘛所说,但我另外使用loopback.getModel
server.js
const loopback = require('loopback'); const ModelInst = require('./model-instnace'); boot(app, __dirname, function (err) { if (err) throw err; ModelInst.event = (loopback.getModel('event')); };
模型instance.js
const ModelInst = { ... event:null ... }
model.js
const models = require('model-instnace Path'); module.exports = function(Transaction) { Transaction.observe('before save', function(ctx, next) { if(ctx.data.code == 3){ models.event.insertNewDate('blah'); } }); };
这对我有效
module.exports = function(Transaction) { Transaction.observe('before save', function(ctx, next) { if(ctx.data.code == 3){ var eventModel = Transaction.app.models.Event; eventModel.create({"nom":"ZONA ABC"}, function(err, obj){ //console.log('eventModel create', err); }); } }); };