我在 Azure 数据库中有两个表,我正在尝试添加一个脚本,每次在事务表中输入内容时,用户都可以将数据插入到一个表字段中。这些表位于不同的架构中,但位于同一数据库中。
当在数据库事务中输入一行时,我需要检查该行中的用户帐户是否在表“UserTable”中,从UserTable中获取记录,然后替换字段“Balance”中的数据
我已尝试以下脚本,但没有任何反应。关于我做错了什么有什么想法吗?
function insert(item, user, request)
{
var userTable = tables.getTable('UserTable');
var total = item.Amount + userTable.Balance;
var data = {
Balance: total,
};
if(userTable.UserAccount === item.UserAccount)
{
userTable.insert(data);
}
request.execute();
}
最佳答案
从 tables.getTable
获取的 userTable
对象为您提供了对表对象的引用。它没有您尝试访问的 Balance
或 UserAccount
属性。您需要做的是首先查询 userTable,然后使用结果进行更新。下面的脚本应该执行与您需要的类似的操作。
function insert(item, user, request)
{
var userTable = tables.getTable('UserTable');
userTable.where({ UserAccount: item.UserAccount }).read({
success: function(results) {
if (results.length === 0) {
// new user. can either return an error, or add
// new entry. Will add a new entry here.
userTable.insert({ Balance: item.Amount }, {
success: function() {
// insert the transaction
request.execute();
}
});
} else if (results.length === 1) {
// Found it. will update the result
var userAccount = results[0];
var total = userAccount.Balance + item.Amount;
userAccount.Balance = total;
userTable.update(userAccount, {
success: function() {
// insert the transaction
request.execute();
}
});
} else {
// Something is wrong
request.respond(
statusCodes.INTERNAL_SERVER_ERROR,
{ error: 'multiple users with same account' });
}
}
});
}
关于Azure插入脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444907/