嘿,我对 Sails 还很陌生。我已经在 sails 中启用了 REST api,不,我只是简单地使用 post 请求主体的主体创建数据,而无需 Controller 的干预。
我定义了两个模型 - users 和 call_log。每次我的应用程序中发生事件时,我希望触发用户表中用户值的更改,但我也想在调用日志表中创建一条日志。
我正在使用 afterCreate()
生命周期方法,并尝试使用 create()
将数据写入第二个表。我似乎没有收到任何错误,但没有任何内容写入 dB。
我的 User.js(模型)
module.exports = {
attributes: {
username: {type: 'string', required: true},
country: {type: 'string'},
},
afterCreate: function (valuesToSet, proceed) {
Talk_log.create({
uid: 'myuid',
partner_uid: 'mypartnerid',
action: 'yeahhh'
}).fetch();
valuesToSet.password = 1244;
return proceed();
},
};
我的 Talk_log.js
module.exports = {
attributes: {
uid: { type: 'string', required: true},
partner_uid: {type: 'string'},
action: {type: 'string'}
},
};
最佳答案
Documentation说“afterCreate 生命周期回调只会在 fetch meta 标志设置为 true 的查询上运行”
所以使用:
User.create().fetch();
Fetch 告诉 Waterline(和底层数据库适配器)在执行 .update()、.create()、.createEach() 或 .destroy() 查询时发回更新/销毁/创建的记录。
你说afterCreate(),但在你的代码中是beforeCreate()。解决这个问题。
关于mysql - Sails.js 无法从其他模型的生命周期在另一个模型中创建数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55943398/