Tuesday, September 10, 2013

Construct nested object graph from SQL hasmany relationship

Construct nested object graph from SQL hasmany relationship

Example: I have some articles and comments and I want to get something
like this:
[{
title: "Article 1",
content: "Super long article goes here",
comments: [
{ author: "Troll", message: "You suck, Sir!" },
{ author: "SpamBot", message: "http://superawesomething.com/"}
]
},{
title: "Article 2",
content: "Another long article goes here",
comments: [ ... ]
}]
Right now I see two solutions:
Get the articles first, then the comments in a second query with some IN
condition and finally add the comments to the respective articles.
Good old joins. For one I will still have to fiddle around with the data a
lot to get into the structure I want. But beyond that I'm a little
concerned since payload like articles.content will be transmitted for
every comment - unless there is a way to do the join I am not aware of.
I'm hoping that my SQL-illiteracy makes me miss the simple solution.

No comments:

Post a Comment