【发布时间】:2016-12-18 05:48:48
【问题描述】:
我正在使用 Waterline ORM 与我的数据库交互。
我将 Waterline.Collections 扩展为一个新对象并将它们分配给一个模块:
var Waterline = require('waterline');
var User = Waterline.Collection.extend({
...some fields...
attributes:{
col_a:{
type:'integer'
},
touch_user:function(){
// increment col_a and update in table
}
}
});
export = module.exports = User;
我查询需要更新的特定模型,然后在 Promise 中操作它们。
database.models.users.findAll().where({'id':1}).then(...model manipulation...)
我经常执行一项任务,几乎每当我访问模型时。我想将此任务封装在与实例关联的函数中,以便我可以简单地调用“touch_user”,并且相关字段将针对我调用它的模型进行更新。
在这样查询模型后,我无法从模型实例访问 Waterline 查询方法(例如 .update()):
database.models.users.findAll().where({'id':1).then((user)=>{
user.touch_user();
//user.update // does not work
});
但直到我查询它,我才检索与记录关联的数据。 我希望 user.touch_user() 在 users 表中增加 col_a ,如下所示
database.models.users.findAll().where({'id':1).then((user)=>{
user.touch_user();
database.models.users.update(user.id, {'col_a':user.col_a+1});
});
上面的问题是用户对象没有准确地反映对表的更新。
【问题讨论】: