gpt4 book ai didi

javascript - Bookshelf.js,在 fetchAll() 方法后更新

转载 作者:行者123 更新时间:2023-12-03 07:02:55 25 4
gpt4 key购买 nike

使用 bookshelf.js,我尝试获取一组对象,然后更新它们。

function markPostsAsSent(postsIds) {
return new Promise((resolve, reject) => {
// Get posts
Search.Post
.where({ id: postsIds })
.fetchAll()
.then(posts => {
// For each post, update sent value
Promise.map(posts.toJSON(), post => post.save({ is_sent: true }))
.then(() => {
resolve(true);
}, err => {
reject(Dependencies.getException(exceptionName, 500, 'POST_UPDATE_ERROR', new Error(), err));
});
}, err => {
reject(Dependencies.getException(exceptionName, 500, 'POST_FETCH_ERROR', new Error(), err));
});
});
}

我试图在 Bookshelf.js 中实现的目标与在 SQL 中实现的目标相同:

UPDATE searches_posts
SET is_sent = true
WHERE id IN (1, 2, 3, 4);

(1, 2, 3, 4) 显然是来自 postsIds 参数的值。

SQL 看起来比 Bookshelf.js 方法简单得多。

是否有更好的方法来同时更新这些行,而不是在 .save() 方法上循环?

最佳答案

你的解决方案看起来很可靠,但是当然,还有更好的方法。例如,您可以明确指定要执行更新 ( http://bookshelfjs.org/#Model-instance-save ),并且可以利用 knex 查询生成器并限制要更新的条目 ( http://knexjs.org/#Builder-whereIn )。

因此,将所有内容放在一起,尝试这样的操作(这是我为了测试解决方案而执行的一些演示示例):

new Person().query(function(qb) {
qb.whereIn('id', [2, 4]);
}).save({
number_of_children: 5
}, {
method: 'update'
}).then(function() {
//Entries with ids 2 and 4 have been updated!
});

希望这有帮助!

关于javascript - Bookshelf.js,在 fetchAll() 方法后更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951885/

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