views:

36

answers:

2

Let's say I have an index action where I want to get a list of projects:

$this->Project->find('all', array('order' => 'Project.modified DESC', 'conditions' => array('Project.user_id' => 1)));

It works well and returns the following array:

Array ( [0] => Array ( [Project] => Array ( [id] => 2 [title] => test project ) ) [1] => Array ( [Project] => Array ( [id] => 1 [title] => first project ) ) )

How do I modify the find function, so it returns the array in the following format:

Array ( [projects] => Array ( [0] => Array ( [id] => 2 [title] => test project ) [1] => Array ( [id] => 1 [title] => first project ) ) )

Thank you!

A: 

You could use the Set::combine() utility method to do this. I've used it for similar means as so:

public function groupByMenu() {
  return Set::combine (
    $this->find ( 
      'all', 
      array (
        'conditions' => array ( 'NavItem.active' => 1 ),
        'order'      => 'NavMenuItem.display_order'
      )
    ),
    '{n}.NavItem.title',
    '{n}',
    '{n}.NavMenu.id'
  );
}

The code above takes a set of navigation items and reorganizes them so that they're grouped by the menu(s) they are displayed within.

Rob Wilkerson
It sort of works for me. Seems weird that Cake doesn't have an easier way of changing the output array by, let's say, by setting up the model differently.Thanks!
John Space
A: 

It's not really clear if it's the fact that the result is under 'Project' rather than 'projects', but if you don't like that it's under [0] I believe you could use PHPs array_shift:

$result = $this->Project->find('all', array('order' => 'Project.modified DESC', 'conditions' => array('Project.user_id' => 1)));
$result = array_shift($result);

The result will be:

Array ( [Project] => Array ( [id] => 2 [title] => test project ) ) [1] => Array ( [Project] => Array ( [id] => 1 [title] => first project ) )
Oscar