Creating nested objects

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 http://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

  • Set up a model for Album, and a model for Song.
  • Create a 1-to-many relationship between them
  • In your AlbumController, load the Album with the ID of one, and create an array out of it using toArray().
  • json_encode that array.

This won't create objects like how you've demonstrated, but it's the closest you can get without programmatically looping through each song.