gpt4 book ai didi

javascript - 使用现有记录进行水线多对多更新

转载 作者:行者123 更新时间:2023-12-02 14:27:39 27 4
gpt4 key购买 nike

我正在尝试编写模型的更新,以允许我的应用程序将 Id 数组(或对象 Id 数组)传递到服务器,并让更新函数删除所有现有关系并添加新关系.

例如我发送的数据是:

{
"id":1,
"newIds":[3,4,5,6,7],
}

数据库中当前的 ID 为:

[1,2,3,4,5] 

所以更新后我希望 id 为:

[3,4,5,6,7]

我目前拥有的更新功能是:

var id = req.param('id'),
newIds = req.param('newIds');
User.findOne({id: id})
.exec(function(err, results){
if(err) return res.serverError(err);
var user = results;

if (user){
if (newIds && newIds.length > 0) {
user.ids.add(newIds);
}

user.save(function(err) {
if(err) {
return res.serverError(err);
};
result.success = true;
return res.json(result);
});
}
});

但是,当我调用更新时,我收到一个错误,提示关系已经存在(它提示 id 3,4 和 5,因为它们已经存在)。

最佳答案

只需将 add() + save() 替换为 update() 即可。

var id = req.param('id'),
newIds = req.param('newIds');
User.update({id: id}, {ids: newIds})
.then(function(updatedUser) {
result.success = true; // assuming you've defined result somewhere earlier
return res.json(result)
})
.catch(res.serverError)

参见:http://sailsjs.org/documentation/reference/waterline-orm/models/update

An array of primary key values passed to .update() for a collection association will set the association to contain only the records with those primary key values provided. That is- it unlinks all other records from the association.

关于javascript - 使用现有记录进行水线多对多更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38098467/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com