0
votes

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?

1
I think you have your data organized incorrectly. Company should hasMany CompanyUser, correct? Then the array should probably be something more like array('Company' => array(...), 'CompanyUser' => array(array('user_id' => 1, 'user_role' => 'admin'), ...); - Kai
you're right!! please, post your answer as a "complete answer" so I can vote you. - marc casas

1 Answers

1
votes

When saving a hasMany relationship, the array should look like this:

array(
  'Company' => array(...), 
  'CompanyUser' => array(
      array('user_id' => 1, 'user_role' => 'admin'), 
      ...
    )
);