与FetchAll相关的BookshelfJS限制不起作用
我有一个hasMany
belongsTo
boxes
和box_states
之间的关系。
我想抓住他们最新的状态,所以这是我的查询:
new Box() .orderBy('id', 'ASC') .fetchAll({ withRelated: [{ 'states' : function(qb) { qb.limit(1) .orderBy('id', 'DESC'); } }] }) .then(function (boxes) { res.json(boxes); });
这将返回所有的框,但只有最后一个框有一个关系; 一切都没有关系。
帮助将不胜感激。
那么,这个工作非常符合预期。 如果你debugging你的解决scheme,你会看到这样的东西(我给你我的例子,它和你的一样 – 一个城镇,很多地址):
select "addresses".* from "addresses" where "addresses"."town_id" in (1, 2, 3, 4) group by "id" limit 1
这样做基本上只为所有实例select一个(!)相关模型( address
)( addresses.town_id in (1,2,3,4)
段中的addresses.town_id in (1,2,3,4)
)。
所以基本上你需要做的是对主要结果进行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); }); });
我不确定是否有更好的select…这个工作。
现在做这个最好的方法(Bookshelf的最新版本)是使用一个集合。 尽pipewithRelated
在.fetchAll()
不可用,但在集合上使用.fetch()
时可用。 请参阅http://bookshelfjs.org/#Collection-instance-fetch