tags:

views:

424

answers:

2

Using Model->find('all') returns an array with the following structure:

array(
  0 => array('Model1' => array(/* Model1 fields*/), 'Model2' => array(/* Model2 fields*/), ...),
  1 => array('Model1' => array(/* Model1 fields*/), 'Model2' => array(/* Model2 fields*/), ...),
  ...)

When a single Model is queried (i.e. Recursive = -1), is it possible to have the results returned as an array with the following structure:

array(0 => /* Model1 fields*/, 1 => /* Model1 fields*/, etc...)

I thought I read this somewhere a while back but cannot figure out how to do this or if it is possible.

A: 

Maybe you are thinking about related models that might get returned this way? AFAIK Cake query results are pretty standardized, and that's a good thing.

array(
    0 => array(
        'Model' => array(
            'id',
            'field1',
            ...
         ),
        'belongsTo/hasOneModel' => array(
            'id',
            'field1',
            ...
         )
        'habtm/hasManyModel' => array(
            0 => array(
                'id',
                'field1',
                ...
            ),
            1 => array(
                ...
            )
        )
    ),
    1 => array(
        'Model' => array(
            ...
        ),
        ...
    )
)

As you can see, the related HABTM or hasMany models are returned in a "flat" array, but the primary model should always contain the model name.

deceze
A: 

You could also modify that model's aftersave method so that it returns $data['Modelname'] after it performs the query... In essence, it'd basically be an array shift and you would only have $arrayname['fieldname'] rather than $arrayname['Model']['fieldname']. Is that what you were asking?

Travis Leleu
Thanks. I was able to achieve my desired functionality by defining the afterFind method and flattening the results there. foreach($results as $index => $values) { $results[$index] = $values['ModelName']; }
Lawrence Barsanti