Chito Cheng
Chito Cheng

Reputation: 550

cakephp 2.X doing update/save for 2 models/tables

I have 2 tables/models (don't have any relation with each other) which have to be updated at the same time, and if either one can't complete the update process, the other one won't be updated....

if I try

if($this->model1->save($data))
   $this->model2->save($data)

the model1 will be updated, no matter the model2 is successfully saved or not.

is this any rollback function that I undo the first save action if the second save action fails

Upvotes: 1

Views: 1157

Answers (1)

pixelistik
pixelistik

Reputation: 7830

You could explicitly begin and commit/rollback transactions, as suggested in a comment by Ross.

But CakePHP even supports this out of the box with saveAssociated(). You can just pass data for both your models:

For saving a record along with its related record having a hasOne or belongsTo association, the data array should be like this:

$data = array(
      'User' => array('username' => 'billy'),
      'Profile' => array('sex' => 'Male', 'occupation' => 'Programmer'),
);

$Article->saveAssociated($data);

There's an option atomic which controls the use of transactions:

atomic: If true (default), will attempt to save all records in a single transaction. Should be set to false if database/table does not support transactions.

If validation fails for one of the models, the other one won't be saved either.

Note that your database needs to support transactions. For MySQL, only the InnoDB storage engine has transaction support, MyISAM doesn't. See comparison of MySQL storage engines.

Upvotes: 2

Related Questions