shoopdelang
shoopdelang

Reputation: 995

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?

Upvotes: 11

Views: 4404

Answers (2)

MSR
MSR

Reputation: 510

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

Upvotes: 2

Predominant
Predominant

Reputation: 1460

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.

Upvotes: 20

Related Questions