- Introduction
- Basic using Transaction
- The problem with method saveMany()
- Solution
- References
1.Introduction
This is my first Tutorial, I would like to talk about using transaction with saveMany() method of Model Object in CakePHP.
2.Basic using Transaction
With CakePHP, using transaction is easy with following simple lines:
// Getting DataSouce
$dataSource = $this->getDataSource();
// Starting transaction
$dataSource->begin();
// do something and save data to talbe
......................
To commit transaction on success
dataSource->commit();
Or rollback transaction on failure
$dataSource->rollback();
It works well when is used with methods: save, saveAll.
3.The problem with method saveMany()
But may be you will spend much time to debug and find problem because transaction seem doesn't work with saveMany() method of Model Object
I was surprised and spent too much time to understand why transaction didn't work with following code block. Although I started transaction, but data is always written to database whether $successFlag is true or false.
// Getting DataSouce
$dataSource = $this->getDataSource();
// Starting transaction
$dataSource->begin();
// Perform some tasks
$items = array();
foreach ($postedData as $row) {
$items[] = array(
'name' => $row['name'],
'quantity' => $row['quantity'],
// something else ...
);
} // End foreach
$this->create();
$this->saveMany($items);
$successFlag = doSomething();
if ($successFlag) {
dataSource->commit();
} else {
$dataSource->rollback();
}
4.Solution
To resolve problem, we must change this line
$this->saveMany($items);
↓
$this->saveMany($items, array('atomic' => false));
5.References
To get more detail : http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array
Thank you for reading and happy coding day.