When I request to include a nested model - for example, GET /api/Widgets/1?filter={include: {"foos": "bars"}}
- I get a duplicate foos
in my results. I thought it was due to LEFT JOIN or something like that since I use MySQL, but when I run LoopBack in debug mode loopback:connector:mysql
, I see that the request for the initial widget works once, but the request for foo it is executed twice, and the query for the line is run twice. Why is this behavior happening, and what can I change (my models, my code, or my expectations)?
Models:
{ "name": "Widget", ... "relations": { "foos": { "type": "hasMany", "model": "Foo", "foreignKey": "widgetId" } } } { "name": "Foo", ... "relations": { "bars": { "type": "hasMany", "model": "Bar", "foreignKey": "fooId" }, "widget": { "type": "belongsTo", "model": "Widget", "foreignKey": "" } } } { "name": "Bar" ... "relations": { "foo": { "type": "belongsTo", "model": "Foo", "foreignKey": "" } } }
Results:
{ id: 1 foos: [ { id: 2, bars: [ { id: 3 } ] }, { id: 2, bars: [ { id: 3 } ] } ] }
Pending:
{ id: 1 foos: [ { id: 2, bars: [ { id: 3 } ] } ] }
This is paraphrased SQL, which, as I see it, is executed for this query:
SELECT `...` FROM `Widget` WHERE `id`=1 ORDER BY `id` LIMIT 1 SELECT `...` FROM `Foo` WHERE `widget_id` IN (1) ORDER BY `id` SELECT `...` FROM `Foo` WHERE `widget_id` IN (1) ORDER BY `id` SELECT `...` FROM `Bar` WHERE `foo_id` IN (2) ORDER BY `id` SELECT `...` FROM `Bar` WHERE `foo_id` IN (2) ORDER BY `id`
I am using Loopback 3.x.
Update: While the request GET /api/Widgets/1?filter={include: {"foos": "bars"}}
demonstrates this behavior, executing Widgets.findById(id, {include: {"foos": "bars"}})
server side works fine. So, for now, I will create a remote method that does this, and possibly an error message file with LoopBack.