cakePHP - conditional save, can it be done?
Scenario:
The method in the controller that saves the data is using some c开发者_Python百科omplex calculations on the results of the first Model->save()
call.
The result then saved in a related-associated model. sometimes it fails..
Is there a built-in way to do it with cake, which will delete the first record when the second save has failed?
If you absolutely can't do these calculations in the app without first saving into the database, use Transactions:
$dbo = $this->Model->getDataSource();
$dbo->begin($this->Model);
$this->Model->save(...);
/* here be dragons */
if (/* success */) {
$dbo->commit($this->Model);
} else {
$dbo->rollback($this->Model);
}
That requires that you use a database and storage engine that supports transactions, like MySQL's InnoDB.
精彩评论