在模型中有一个名为 counter 的字段,每当我调用像
这样的自定义远程方法时Request URL
http://loopback:3000/api/models/increment_counter
Request body
EMPTY
Response
{
"counter" : [Value after Increment]
}
目前要增加首先我必须从数据库中获取计数器值并将其增加一个并更新 couter 值,这涉及两个查询,是否可以像下面的 mysql 查询一样在单个 NodeAPI 调用中完成它。我是目前使用 Mysql 作为数据库。
mysql_query("
UPDATE model
SET counter = counter + 1
WHERE model_id = '1'
");
谢谢
最佳答案
鉴于您想要的 MySQL 语法,您似乎需要一个原子计数器。
数据库事务
通过 MySQL 连接器,您可以使用 database transactions . MySQL 连接器支持它。对于原子计数器来说有点矫枉过正,但它会完成工作。
这是一个例子,在自定义远程方法中
MyModel.someRemoteMethodForIncrementing = function(callback) {
// Start the transaction
MyModel.beginTransaction({
isolationLevel: MyModel.Transaction.READ_COMMITTED
}, function(err, tx) {
// Retrieve the current counter value as part of the transaction
MyModel.findById(id, {
transaction: tx
}, function(err, data) {
if (err) {
console.log(err);
return tx.rollback(function(err) {
callback(err);
});
}
// Increment the counter as part of the transaction
var inc = data.counter + 1;
MyModel.updateAttributes({
counter: inc
}, {
transaction: tx
}, function(err, newData) {
if (err) {
console.log(err);
return tx.rollback(function(err) {
callback(err);
});
}
// Commit the transaction to make it happen
tx.commit(function(err) {
if (err) return callback(err);
// Counter should have been incremented
callback();
});
});
});
});
};
我还没有测试过,但应该可以,让我知道
扩展运算符
将来,您将能够使用 $inc (increment) extended operator但到目前为止,只有 MongoDB 连接器支持它,MySQL 不支持。
仅供引用,语法如下(仅适用于 MongoDB)
PUT api/Model/:id?filter={"$inc":{"name":propertyToIncrement, "count":incrementAmount}}
正在进行 PR我正试图登陆以获得 MySQL 支持,但是有 many things在合并之前完成。
关于mysql - 在环回中使用远程方法增加模型中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40754819/