I have three simple models:
- Users
- Companies
- CompaniesUsers (hasMany through relation between Users and Companies)
As AD7six tell me in this question (How to organize CakePHP code?), I'm using saveAssociated() to persist a Company and a CompanyUsers (with a "link" to Users), but I'm doing something wrong:
public function add() {
if ($this->request->is('post')) {
$this->request->data['CompanyUser'] = array (
'user_id' => $this->Auth->user('id'),
'user_role' => 'admin'
);
debug($this->request->data);
if ($this->Company->saveAssociated($this->request->data)) {
return $this->redirect($this->Auth->redirect());
}
}
}
The Company is saved (looking at the SQL log), but CompanyUser not. The content of $this->request->data is:
array(
'Company' => array(
'name' => 'will this work?',
'vat_number' => 'maybe...'
),
'CompanyUser' => array(
'user_id' => '1',
'user_role' => 'admin'
)
)
And the problem is that the content of the CompanyUser "key" is ignored. Cake tries to add a CompanyUser, but only filling the "company_id", "created" and "modified" fields, so MySQL throws an "Integrity Constraint Violation" for the "user_id" field. And the "user_role" (a field of CompanyUser) isn't added.
What I'm doing wrong, here?
array('Company' => array(...), 'CompanyUser' => array(array('user_id' => 1, 'user_role' => 'admin'), ...);- Kai