0

I've got my models set up so that Users belong to Groups. There is a working HABTM relationship between these two.

The code below is used to populate the database with some demo data. Prior to the following snippet, the Groups table has been filled with some sample group data.

The code snippet below works. It adds records to the Users table and the join table (groups_users) gets the correct entries, too. So basically, the HABTM relationship works fine.

Here is my question: How do I add associations with multiple groups instead of just the single relationship? Doing a

'Group'=>array($group1, $group2)
instead of the
'Group'=>$group1'
as outlined below does NOT work. When I use an array, nothing at all is added to the join table.

Your help is greatly appreciated!

$groups = $this->Group->find('all');
  for ($i=0; $i<=200; $i++) {                   
$groupIndex1 = rand(0, count($groups)-1);
$groupIndex2 = rand(0, count($groups)-1);

$this->User->set(
  array(
    'id'=>null,
    'name'=>'Dummy User '.$i0,
    'Group'=>$groups[$groupIndex1]
  )
);
$this->User->save();
tereško
  • 58,060
  • 25
  • 98
  • 150
Ralf
  • 2,512
  • 4
  • 24
  • 26

1 Answers1

0

To save multiple groups for a single user, you will have to define hasMany relationship in your User model. And in your saving code it will looks like:

$groups = $this->Group->find('all');
for ($i=0; $i<=200; $i++) {                   
$groupIndex1 = rand(0, count($groups)-1);
$groupIndex2 = rand(0, count($groups)-1);
$data  = 
  array('User' => array(
                        'id'=>null, 
                        'name'=>'Dummy User '.$i0,
                       ),
        'Group'=> array($groups[$groupIndex1], $groups[$groupIndex2])
  )
);
$this->User->saveAssociated($data, array('deep' => true);

This link might help you to understand 'deep' => true option.

Arun Jain
  • 5,476
  • 2
  • 31
  • 52