使用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()方法上循环?
发布于 2016-05-07 09:52:10
你的解决方案似乎是可靠的,但当然,还有更好的方法。例如,您可以显式地指定要执行更新(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!
});希望这能有所帮助!
发布于 2016-05-08 18:54:09
更新/插入呢?有什么更有说服力的方法来做到这一点呢?
yield Promise.map data, (oneEvent)->
eventModel = new Event oneEvent
eventModel.fetch().then (fromDB) ->
return do eventModel.save if not fromDB?
fromDB.save oneEventhttps://stackoverflow.com/questions/36951885
复制相似问题