AshHimself
AshHimself

Reputation: 4112

Structure JSON output in cakePHP

What is the simplest and best practice way to customise the JSON output in cakephp 2.x.

I have the following in my controller:

$questions = $this->Question->find('threaded', array(
  'fields' => array(
    'label',
    'id',
    'parent_id',
    'load_on_demand'
   ),
  'order' => array('lft ASC') 
));

$questions= $this->set('questions', $questions);

$this->set('_serialize', 'json');

I have the following JSON (truncated);

{
    "Question": {
        "id": "27",
        "parent_id": "0",
        "load_on_demand": "true",
        "label": "Main Menu"
    },
    "children": [
        {
            "Question": {
                "id": "28",
                "parent_id": "27",
                "load_on_demand": "true",
                "label": "Web Development"
            },

but I need it to be like the following example in jqTree;

{
    label: 'node1',
    children: [
        { label: 'child1' },
        { label: 'child2' }
    ]
},
{
    label: 'node2',
    children: [
        { label: 'child3' }
    ]
}

Upvotes: 0

Views: 162

Answers (2)

Just use the Hash class before setting the results:

function buildQuestion(){

$questions = $this->Question->find('all', array(
  'fields' => array('label', 'id', 'parent_id','load_on_demand'),
  'order' => array('lft ASC')
));

 $results = Hash::extract($questions, '{n}.Question');
 $results = Hash::nest($results, ['idPath' => '{n}.id', 'parentPath' => '{n}.parent_id');

Upvotes: 3

Momin
Momin

Reputation: 868

First of all, you shouldn't use find for these custom labeling or Rest api code. its simply because using any ORM might fetch extra data/object to that api, consuming lots of memory for bulk requests. Use sql like :

Select `Question`.`id` as `id`, .....
from `Question`
INNER JOIN `children` on `children`.`parent_id` = `Question`.`id`
where .......
//I cant say much about the query as the model aint clear to me

This might help if you want to add extra field. remember to alias the fields needed.

Upvotes: 0

Related Questions