0

Cake Php Read function to retrieve result as simple array

$result = $this->Model->read('id, name, title', $id);

It will result as

Array
(
    [Model] => Array
    (
        [id] => 1
        [name] => test
        [title] => New Head title
    )

)

It there any way to retrieve result array directly from query as below

Array
    (
        [id] => 1
        [name] => test
        [title] => New Head title
    )

Without using any temp storage of a variable.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Justin John
  • 9,223
  • 14
  • 70
  • 129
  • 3
    There are ways to do that, but why? The default Cake result structure includes the model name, since that's important when fetching associated records. I'd recommend to simply get used to that. – deceze May 21 '12 at 06:29
  • @deceze Currently I am on project, where I avoided all the associated records in models to better performance ... So default Cake result structure don't have any positive effect in results. – Justin John May 21 '12 at 07:44
  • what you are trying to do will hurt performance as well as usability more than anything in the (cake)world. so your whole point is pointless to me! – mark May 21 '12 at 08:53

3 Answers3

2

Just run the result through a Set::extract call, like this:

$result = $this->Model->read('id, name, title', $id);
$result = Set::extract('/Model', $result);

Set is a very powerful class, I suggest you read on it. :) Cheers.

Borislav Sabev
  • 4,776
  • 1
  • 24
  • 30
0

CakePHP purity aside (agree with other posters though)

Is find('list') what you are looking for?

$result = $this->Model->find('list', array('fields' => array('id', 'name', 'title'),        'conditions' => array('id' => $id), 'recursive' => 0    ));
jonoaustin
  • 45
  • 5
0

Unless you're going to hack the Cake core, Cake will always internally return the results using the extra model key. So "without using any temp storage of a variable" is pretty much impossible, if you mean this in terms of "speed optimization" (in quotes, because it hardly makes any difference).

You can make it work simply with:

$result = current($this->Model->read('id, name, title', $id));

You could override the model's read method so it always does this internally (not recommended, it'll come to bite you one day). You could do so in the AppModel to have this behavior globally.

deceze
  • 510,633
  • 85
  • 743
  • 889