0

In a CakePHP, app, let's assume I have two models: Team and User. Those models are associated with each other in a HABTM relationship (joined by table teams_users).

Say we have a form where someone can specify details to create a new Team and User, at the same time.

What is the cleanest, most straightforward way to create those records simultaneously, with an association to each other?

What are the "gotchas" for naming form fields, and processing in the Controller?

I want to do this in the most Cake friendly way, so that I'm able to return validation errors on both models.

Benjamin Allison
  • 2,134
  • 3
  • 30
  • 55

1 Answers1

0

This method would go into your Team model, assuming all assocs and HABTM are set up right.

public function createTeam($postData) {
    $this->set($postData);
    $this->User->set($postData);
    $validTeam = $this->validates();
    $validUser = $this->User->validates()

    if ($validTeam && $validUser) {
        $this->create();
        $this->save($postData, array('validate' => false);
        $this->User->create();
        $this->User->save($postData, array('validate' => false);
        $this->TeamsUser->create();
        $this->TeamsUser->save(array(
            'TeamsUser' => array(
                'user_id' => $this->getLastInsertId()
                'team_id' => $this->User->getLastInsertId()
            )
        ));
        return true;
    }
    return false;
}
floriank
  • 25,546
  • 9
  • 42
  • 66
  • I can see how this would work! Is Cake just not able to create an association via a simple saveAll() or saveAssociated()? It's kind of a bummer all that extra code is required. Hopefully 3.0 streamlines this sort of thing! – Benjamin Allison Mar 02 '14 at 23:06
  • The issue I'm finding is that, in trying to save two models via the same form, that only one model's field validation errors show up... – Benjamin Allison Mar 03 '14 at 02:18
  • saveAll() should save both records but I don't think it will create the join table record. saveAll() was a bitch in the past anyway. I don't know why you see only errors for one, very similar code with even more models works well for me. – floriank Mar 03 '14 at 11:21
  • Ah, I get errors, one model at a time, not all at once. That's fine. Also, you're missing some closing brackets on the two `validate => false` lines, and a comma in the array. You must use Sublime Text too! :) Thanks! – Benjamin Allison Mar 03 '14 at 13:35
  • I wrote that down without using any IDE, I'm using phpstorm with phpcs support enabled usually. I've updated the answer to fix your issue, forgot that myself. The reason is you have to define the vars is simply when the first model validation fails it wont run the 2nd and by this you wont get the errors for the 2nd. – floriank Mar 03 '14 at 14:31