>我有一个要更新的对象数组,因此需要多次更新。我正在寻找实现这一点的最佳方法。每个对象包含相同的属性,但每个对象的属性具有不同的值。
我是否实现这样的东西?
var people = [
{'firstName': 'Brian', 'clockedIn': '2016-4-12', 'type': 'developer'},
{'firstName': 'Taylor', 'clockedIn': '2016-4-14', 'type': 'developer'},
{'firstName': 'Jake', 'clockedIn': '2016-4-14', 'type': 'manager'}
];
PersonModel.update({'type': 'developer'}, people, function(err, records) {
// ...
// ...
});
如果我执行类似于前面的代码的操作,它到底做了什么?它是否自动尝试匹配 people 数组中每条记录的主键,更新列出的任何属性,然后将更新的记录传递到回调函数中?
我注意到在 Sails.js 文档中,更新函数的第二个参数可以是对象或数组,我只是不清楚我是否可以像这样使用它。文档不清楚。
如果我不能像这样使用它,并且我想尝试迭代或递归方法,您建议我如何实现它?
你的适配器是什么?
我必须用MySQL来做这件事,我自己做查询,然后调用PersonModel.query(myQuery)
我按照这个答案来制作它(有两个字段的示例):
values = [
{
id: 1,
param_1: 'NewValueParam1',
param_2: 'NewValueParam2'
},
{
id: 2,
param_1: 'AnotherNewValueParam1',
param_2: 'AnotherNewValueParam2'
}
];
function multiValuesUpdate(values) {
var request = "UPDATE MyTable SET ";
var part_param_1 = "`param_1` = (CASE `id` ";
var part_param_2 = "`param_2` = (CASE `id` ";
var part_ids = "WHERE `id` IN (";
_.forEach(values, function (v) {
part_param_1 += "WHEN '" + v.id + "' THEN '" + v.param_1 + "' ";
part_param_2 += "WHEN '" + v.id + "' THEN '" + v.param_2 + "' ";
part_ids += v.id + ",";
});
part_param_1 += "ELSE `param_1` END), "; // Be careful with the comma !
part_param_2 += "ELSE `param_2` END) ";
part_ids = part_ids.slice(0, -1) + ");"; // Remove the last "," and add ");"
request += part_param_1 + part_param_2 + part_ids;
return request;
}
console.log(multiValuesUpdate(values));
输出:
"UPDATE MyTable
SET `param_1` = (
CASE `id`
WHEN '1' THEN 'NewValueParam1'
WHEN '2' THEN 'AnotherNewValueParam1'
ELSE `param_1`
END),
`param_2` = (
CASE `id`
WHEN '1' THEN 'NewValueParam2'
WHEN '2' THEN 'AnotherNewValueParam2'
ELSE `param_2`
END)
WHERE `id` IN (1,2);"