I've tried searching for an answer to this, as I'm sure its something that's been sorted out before, but I couldn't find anything discussing how cakephp formats the data returned from a Model. Normally I just see how the data comes, and handle it as needed for each Controller/View. In this case however, I want to reuse my views, unfortunately the way cakephp hands me the data from different controllers is causing me problems.
I have 2 models,associated as follows :
class Group extends AppModel {
public $hasMany = array( 'User' );
}
class User extends AppModel {
public $belongsTo = array(
'Group' );
}
I want to have View/Groups/view/id
show me details for the individual groups, as well as a list of users that belong to the group. Ideally, I don't want to recreate the code to display the user list, as it already exists in the View/Users/index
I found that I can use $this->extend('/Users/index') but I can't just use `$this->set('users',$group['User']), like I want, because the array is built differently.
In UsersController::index() I would call $users = $this->find('all');
which gives a list of users like this : debug($users);
array(
(int) 0 => array(
'User' => array(
'id' => '100',
'group_id' => '101',
)
),
(int) 1 => array(
'User' => array(
'id' => '101',
'group_id' => '101',
)
)
)
In GroupsController is use $this->Group->contain(array('User')); $group = $this->GroupsController->Group->find('first','conditions'=>array('id'=>$id);
Which returns a list of Groups, but in this format instead debug($group['User']);
'User' => array(
(int) 0 => array(
'id' => '101',
'group_id' => '101',
),
(int) 1 => array(
'id' => '100',
'group_id' => '101',
)
)
Is there anyway I can change how I call for my model data, to have it passed in a consistent manner on different Controllers, whether it is the main model or associated model? Or will I just have to cycle through the data each time and rebuild the data in the right format? This seems like once my dataset grows it will become an efficiency concern.