php - CakePHP: How to control the structure of data returned by find() method -
in testscontroller.php
i'm using find()
method...
$r = $this->question->find('all', array('conditions' => $conditions ));
...and resulting data looks this:
array( (int) 0 => array( 'question' => array( 'id' => '2', 'created' => '2013-02-13 14:15:16', 'modified' => '2013-04-18 09:10:03' ), ), ...
notice how each item in array wrapped inside another array. i'd make structure of array consistent how i'm using elsewhere play nicely elements , other code expect structure match when set variables inside controller...
$question = $this->question->findbyid($id); $this->set('question', $question);
...which results in this:
array( 'question' => array( 'id' => '1', 'created' => '2013-04-04 15:25:54', 'modified' => '2013-04-04 15:25:54' ), ...
the differences i'm aware of second example users findbyid()
method, , it's maybe relevant find()
in first example inside different model's controller.
is there way make them match?
(i know manually re-shuffle data array_map()
rather understand why different , not have to.)
as @dave said, it's natural have numbered arrays when expecting multiple records, find('list'), find('all')... well, except find('first').
it's matter of knowing type of records expecting get.
however, if decided change functionality , have every record numbered arrays make consistent, there's way changing 1 file.
in appmodel
public function afterfind($results, $primary = false) { if(!set::numeric(array_keys($results)) { $results= array($results); } return $results; }
that way, find() methods return
array( (int) 0 => array( 'question' => array( /*data*/ ), ), ...
even if it's 1 record.
warning: haven't tried in appmodel, in specific cases, test functionality , keep adjusting code until every case covered. things might produce errors: $results
no results, , when retrieving associated data other model. watch out because function isn't definitive , have play bit (probably)
Comments
Post a Comment