BadHorsie
BadHorsie

Reputation: 14554

CakePHP 1.3 - Transaction for saving models that aren't related

How do I start a transaction in a controller, then attempt to save multiple models that have no relation to each other? If anything fails, obviously I wish to rollback, and if everything worked then commit.

I guess my question is which model do I start the transaction on?

$datasource = $this->Car->getDataSource();
$datasource->begin($this->Car);

$car = $this->Car->save();
$dog = $this->Dog->save();
$house = $this->House->save();

if ($car && $dog && $house) {
    $datasource->commit($this->Car);
} else {
    $datasource->rollback($this->Car);
}

Will this work to ensure Dog and House save as well as the Car? i.e. Does it matter which model the transaction is started on?

Upvotes: 2

Views: 2227

Answers (1)

ianmjones
ianmjones

Reputation: 3415

It doesn't matter which model you use to start the transaction, but generally people use the model "closest" to the controller if there is one.

$continue = true;
$this->Car->begin();

// Do stuff that might set $continue to false.

if ($continue) {
    $this->Car->commit();
} else {
    $this->Car->rollback();
}

To set $continue during the "Do stuff" bit, check each save etc.

if (!$this->Car->save()) {
    $continue = false;
}

if ($continue) {
    if (!$this->Dog->save()) {
        $continue = false;
    }
}

if ($continue) {
    if (!$this->House->save()) {
        $continue = false;
    }
}

Upvotes: 6

Related Questions