Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redundant ModelName in CakePHP find Results

I am trying to get rid of the redundant model names in the results array returned by the find method in CakePHP. As it is now, if I were to do something like $results = $this->Model->find('all'), I would have to access a result field by $results[Model][fieldName] instead of $results[fieldName].

I understand that having the model name in the array has benefits but I am trying to build an api so I need to json encode the array. With the model name included I get something hideous like:

[{"Model":{"field":"blah","field":"blah"}},{"Model":{"field":"blah","field":"blah"}}]

I want something more elegant like:

[{"field":"blah","field":"blah"},{"field":"blah","field":"blah"}]

Any ideas?

like image 818
shoopdelang Avatar asked Aug 09 '12 04:08

shoopdelang


2 Answers

In your controller, instead of serializing the results of the find, serialise a level deeper.

Assuming CakePHP 2:

$things = $this->Thing->find('all');
$things = Set::extract('/Thing/.', $things);

Now your results should be free of the extra level in your JSON.

The alternative, lengthy way of doing it is to for loop over the results:

foreach ($things as $k => &$v) {
    $v = $v['Thing']
}

After that, your $things will have removed the extra level of keys.

like image 179
Predominant Avatar answered Nov 12 '22 09:11

Predominant


For later versions of Cake, use $things = Set::extract($things, '{n}.Thing');

like image 2
MSR Avatar answered Nov 12 '22 09:11

MSR