Closed mo86 closed 5 years ago
Why not use $connection->transactional()
? It does pretty much exactly what you have in your code, but doesn't require a try/catch.
Thx I didnt know about that. But I still think it would be great to add a more complex saving example with two or more models/tables and the use of the last insert id as a foreign key for the following tables inside a transaction. Maybe we could add a "best practises" category to the documentation where we show how to solve common problems in the "cake way". I mean a collection of example code with a short summary. Just an idea.
I am not sure a best practices section would age well. I have seen them just collect all sorts of information that could fit into the documentation relevant to each sample.
Normally you shouldn't need to use last insert id. The ORM can automatically connect foreign key data together.
Thx I didnt know about that. But I still think it would be great to add a more complex saving example with two or more models/tables and the use of the last insert id as a foreign key for the following tables inside a transaction.
$result=$this->Users->connection()->transactional(function() use ($user,$profile){
if ($this->Users->save($user)) {
// .....
$profile->user_id = $user->id;
if ($this->Users->Profiles->save($profile)) {
//other logic
return true;
}
}
return false;
});
if($result){
$this->Flash->success(__('....'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('........'));
}
I think book.cakephp.org
and API documentation is clear enough
I would like to add an example code snippet to the documentation where we explain the best practise for a complex saving operation using a transaction and a try/catch block.
For example I want to do 2 inserts into different tables. But the second insert should only be done when the first insert was done without errors.
My approach:
What do you think about? Is there a better approach? I would like to hear your opinion :)