【问题标题】:BookshelfJS limiting withRelated in FetchAll doesn't workBookshelfJS 在 FetchAll 中限制 withRelated 不起作用
【发布时间】:2015-05-08 19:04:13
【问题描述】:

我在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);
    });

这会返回所有的盒子,但只有最后一个盒子有一个关系;一切都没有关系。

我们将不胜感激。

【问题讨论】:

    标签: node.js backbone.js bookshelf.js


    【解决方案1】:

    嗯,这和预期的差不多。如果你调试你的解决方案,你会看到这样的东西(我给你我的例子,它与你的关系相同 - 一个城镇,许多地址):

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

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

    所以基本上你需要做的是 foreach 主要结果并在每个结果上转到 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);
        });
    
    });
    

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

    【讨论】:

      【解决方案2】:

      现在最好的方法(最新版本的书架)是使用集合。尽管withRelated.fetchAll() 中不可用,但在集合上使用.fetch() 时可用。见http://bookshelfjs.org/#Collection-instance-fetch

      【讨论】:

        猜你喜欢
        • 2019-10-10
        • 1970-01-01
        • 2013-02-05
        • 2014-02-25
        • 2016-04-16
        • 2015-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多