BookshelfJS 限制 withRelated 在 FetchAll 中不起作用

BookshelfJS limiting withRelated in FetchAll doesn't work

我在 boxesbox_states 之间有一个 hasManybelongsTo 的关系。

我想抓取所有箱子的最新状态,所以这是我的查询:

new Box()
    .orderBy('id', 'ASC')
    .fetchAll({
        withRelated: [{
            'states' :  function(qb) {
                qb.limit(1)
                    .orderBy('id', 'DESC');
            }
        }]
    })
    .then(function (boxes) {
        res.json(boxes);
    });

这个returns所有的box,只有最后一个box有一个关系;一切都没有关系。

不胜感激。

好吧,这和预期的差不多。如果调试您的解决方案,您会看到类似这样的内容(我给您的示例与您的示例具有相同的关系 - 一个城镇,多个地址):

select "addresses".* from "addresses" where "addresses"."town_id" in (1, 2, 3, 4) group by "id" limit 1

这基本上是 select 所有实例(addresses.town_id in (1,2,3,4) 段)的一个(!)相关模型(address)。

所以基本上您需要做的是获取主要结果,然后 withRelated 处理每个结果。

new Town().fetchAll().then(function(towns) {

    var my_towns_with_only_last_address = [];

    Promise.map(towns.toJSON(), function(town) {
        return new Town({
            id: town.id
        }).fetch({
            withRelated: [{
                'address': function(qb) {
                    qb.limit(1);
                    qb.orderBy('id', 'desc');
                }
            }]
        }).then(function(result) {
            return my_towns_with_only_last_address.push(result.toJSON());               
        });
    }).then(function() {
        res.json(my_towns_with_only_last_address);
    });

});

我不确定是否有更好的选择...这行得通。

现在(最新版本的 Bookshelf)执行此操作的最佳方法是使用集合。虽然 withRelated.fetchAll() 中不可用,但在集合上使用 .fetch() 时可用。参见 http://bookshelfjs.org/#Collection-instance-fetch