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

Bookshelf.js, update after fetchAll() method

使用 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) and you can tap into the knex query builder and limit which entries you want to update (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!
});

希望对您有所帮助!

那update/insert呢?还有什么 eloquent 方法可以做到这一点?

yield Promise.map data, (oneEvent)->
  eventModel = new Event oneEvent

  eventModel.fetch().then (fromDB) ->
    return do eventModel.save if not fromDB?
    fromDB.save oneEvent