Using transactions
Saving data for several models at once could lead to orphaned data if some validation breaks along the way. It's always good practice to use atomic save operations when related data needs to make it to the database together.
CakePHP provides the saveAssociated()
, saveMany()
, and saveAll()
model methods to store your data using an atomic operation, but sometimes, you'll want to use a database transaction to manage it. Find more details on these methods at http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array.
Note
Your database tables must allow transactions. For example, the InnoDB storage engine, which ships with MySQL, implements transactions. Please check your database documentation to confirm if your current storage engine allows transactions.
Getting ready
For this recipe, we'll use the packages
and warehouses
tables and related models from previous recipes, where Package
hasMany Stock
(or where Stock
is defined...