M41DZ3N
M41DZ3N

Reputation: 346

Saving data with HABTM and HasMany looses foreignKey

I have a User model with two relations:

  1. HasAndBelongsToMany

    public $hasAndBelongsToMany = array(
        'group' => array(
            'className' => 'group',
            'foreignKey' => 'user_id'
        )
    );
    
  2. HasMany

    public $hasMany = array(
      'phonenumber' => array(
        'className' => 'phonenumber',
        'foreignKey' => 'user_id'
      )
    );
    

Phonenumber and Group have set

public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id'
    )
);

When I use

$this->saveAll(array(
            'User' => $data, 
            'phonenumber' => $numbers, //array with data
            'group' => $groups //array with data
   )
);

The data gets saved in the tabels but User_id is "0" in phonenumber and group table.

How can I get the correct ID saved ? (CakePHP v 2.5)

Upvotes: 1

Views: 91

Answers (2)

Jeff N
Jeff N

Reputation: 146

FWIW saveAll() should work as advertised, populating the new user_id in the child tables in one fell swoop.

Have you paid attention to the relevant options: atomic & deep?

Especially if database does not support transactions, you'll need to pass in atomic:

$this->saveAll(array(
            'User' => $data, 
            'phonenumber' => $numbers, //array with data
            'group' => $groups //array with data
   ),
   array('atomic' => false)
);

Upvotes: 2

Jonathan
Jonathan

Reputation: 2063

Considering the CakePHP documentation you will find this hint:

When working with associated models, it is important to realize that saving model data should always be done by the corresponding CakePHP model. If you are saving a new Post and its associated Comments, then you would use both Post and Comment models during the save operation (http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto)

Based on that information I suggest you try the following:

$this->User->save($data);  // first save the user

Assuming you have multiple numbers:

foreach($numbers as $key => $nbr) {
    // set user_id related data
    $numbers[ $key ]['Phonenumber']['user_id'] = $this->User->id;
}

Finally save your related data:

$this->User->Phonenumber->saveAll($numbers);

Since this code is untested you may need to take some adjustments. Always ensure to follow the Cake-Conventions and use CamelCase ModelNames.

Upvotes: 0

Related Questions