1
votes

I am working on building a json Rest api with CakePHP. It works great, except I can't seem to get the proper structure to the response.

I two tables: Users and Profiles. Users hasOne Profiles. Profiles has a foreign key. Models: Users.php (with public $hasOne = 'Profile'), Profiles.php Controller: UsersController.php

The response is:

[2] => Array
    (
        [User] => Array
            (
                [id] => 3
                [firstname] => test
                [lastname] => 
                [email] => 
                [password] => 
                [created] => 2012-09-04 16:44:04
                [modified] => 2012-09-04 16:44:04
            )

        [Profile] => Array
            (
                [id] => 
                [skill] => 
                [user_id] => 
            )

    )

I really want the response to be like this:

[2] => Array
    (
        [User] => Array
            (
                [id] => 3
                [firstname] => test
                [lastname] => 
                [email] =>
                [Profile] => Array
                      (
                     [id] => 
                     [skill] => 
                     [user_id] => 
                       )
            )


    )

I have looked in the join(), bind(), containable...I can't seem to find the solution for nested table. Any ides to get Profile to be nested within the Users?

1

1 Answers

1
votes

Cakephp won't do it, since it isn't the structure it uses to manage data. You will have to do it manually. If you are working with a single result (as the given by find('first')) Try something like this (I haven't tested it):

$result = $this->User->find('first', array('conditions' => array('User.id' => 1)));
Set::insert($result, 'User.Profile', $result['Profile']);
uset($result['Profile']);