Вопрос

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.

Это было полезно?

Решение

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;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top