Hello!
I'm building a REST interface and I'm currently evaluating the best way to take a set of nested models and turn them into a nested JSON object without having to write complex PHP.
Consider the following models:
-- Create tables
create table album (
id int(11) unsigned auto_increment primary key,
name varchar(100) not null
) engine=innodb default charset=utf8;
create table song (
id int(11) unsigned auto_increment primary key,
album_id int(11) unsigned not null,
name varchar(100) not null,
index (album_id),
foreign key (album_id) references album(id) on update cascade on delete cascade
) engine=innodb default charset=utf8;
-- Create data.
insert into album (id, name) values (1, "Best of Sonata Arctica");
insert into song (album_id, name) values (1, "The Cage"), (1, "8th Commandment");
Now, I want to make a request to, let's say https://api.example.com/album/1
and receive the following JSON:
{
"id": 1,
"name": "Best of Sonata Arctica",
"songs": [
{
"id": 1,
"name": "The Cage"
},
{
"id": 2,
"name": "8th Commandment"
}
]
}
How would I do this without creating a PHP loof for all the songs in the album and building complex, nested PHP code to render everything?
Thanks for your time.
// dimhoLt