LoginSignup
0
1

More than 5 years have passed since last update.

Using transaction with saveMany() method in CakePHP

Last updated at Posted at 2015-06-19
  1. Introduction
  2. Basic using Transaction
  3. The problem with method saveMany()
  4. Solution
  5. 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:

Item
// 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.

Item
// 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.

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1