@filiberto
To use transactions in CakePHP, you can follow these steps:
1
|
use CakeORMBehaviorTransactionAwareTrait; |
1 2 3 4 |
class User extends AppModel {
use TransactionAwareTrait;
// ...
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Start the transaction
$this->User->getConnection()->begin();
try {
// Perform your database operations here
$user = $this->User->newEntity($data);
if ($this->User->save($user)) {
// Save related data (e.g., address)
$address = $this->User->Address->newEntity($addressData);
$address->user_id = $user->id;
if ($this->User->Address->save($address)) {
// Commit the transaction if all database operations succeed
$this->User->getConnection()->commit();
// Return a success message
return 'User and related data saved successfully.';
}
}
// Rollback the transaction if any of the database operations fail
$this->User->getConnection()->rollback();
} catch (Exception $e) {
// Rollback the transaction on exception (error occurred)
$this->User->getConnection()->rollback();
// Throw the exception or handle it as per your requirement
throw $e;
}
|
By using transactions, you can ensure that all database operations within the transaction are either committed or rolled back atomically, providing data consistency and integrity.