I have two tables and a join table. I tried using the $hasAndBelongsToMany but it didnt work, so instead i create a model for the join table and used.
User hasMany Membership
Membership belongsTo User, Club
Club hasMany Membership.
I have a form that saves to both tables.
function dashboard_add(){
$user = $this->Session->read('User');
$register = false;
if (!empty($this->data)) {
if($this->Club->saveAll($this->data)){
$this->Session->setFlash(__('You have registered your club. You will be contacted soon!', true), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('There was a problem with your registration. Please, try again.', true), 'default', array('class' => 'warning'));
}
}
if (empty($this->data)) {
$this->data = $this->User->read(null, $user['User']['id']);
}
$this->set(compact('register'));
}
The User model has
var $hasMany = array(
'Membership' => array(
'className' => 'Membership',
'foreignKey' => 'user_id'
)
);
The Membership Model has
var $belongsTo = array('User','Membership');
The Club Model has
var $hasMany = array(
'Membership' => array(
'className' => 'Membership',
'foreignKey' => 'club_id'
),
'Upload' => array(
'className' => 'Upload',
'foreignKey' => 'club_id'
)
);
I don’t get any errors. The club table populates, but the membership and user table doesnt insert/update.
UPDATE: debug($this->Club->save($this->data));
Array
(
[User] => Array
(
[id] => 1
[first_name] => this
[last_name] => that
[company_name] => other
[city] => this
[state] => that
[zip] => other
[telephone] => that
[email_address] => this
)
[Club] => Array
(
[address] => fvdfvx
[title] => xcvxcv
[category] => xcvxcv
[modified] => 2012-05-03 06:31:12
)
)
I presume you are using cakePHP 1.3.x. See the documentation to understand how cake saves many models at the same time, you need to generate an array with all models to save.. for example:
http://book.cakephp.org/1.3/view/1031/Saving-Your-Data
Apparently in your $this->data you only have a simple array [User]. and not multiple arrays to save as in the Example.
I hope I have helped.
Regards.