使用单个事务提交和回滚的多个模型的事务管理
我是 cakephp 的新手。 我想知道 cakephp 是否可以通过单个事务处理多个模型提交和回滚。 我想做这样的事情
<?php
function add(){
$transaction = begintransaction;
if(model1->save()){
if(model2->save()){
if(model3->save(){
}
else{
$errorFlag['model3'] = "Error in model 3";
}
}
else{
$errorFlag['model2'] = "Error in model 2";
}
}
else{
$errorFlag['model3'] = "Error in model 3";
}
if(empty($errorFlag)){ //no error in saving the model
$transaction->commit();
$this->Session->setFlash(__('The form data with multiple model is saved', true));
}
else{ //error in saving the model
$transaction->rollback();
$this->Session->setFlash(__('The form data with multiple model is saved', true));
}
}
?>
I am new to cakephp.
I want to know if it is possible in cakephp to to handle multiple model commit and rollback with single transaction.
I want to do some thing like this
<?php
function add(){
$transaction = begintransaction;
if(model1->save()){
if(model2->save()){
if(model3->save(){
}
else{
$errorFlag['model3'] = "Error in model 3";
}
}
else{
$errorFlag['model2'] = "Error in model 2";
}
}
else{
$errorFlag['model3'] = "Error in model 3";
}
if(empty($errorFlag)){ //no error in saving the model
$transaction->commit();
$this->Session->setFlash(__('The form data with multiple model is saved', true));
}
else{ //error in saving the model
$transaction->rollback();
$this->Session->setFlash(__('The form data with multiple model is saved', true));
}
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的模型 1-3 具有“有许多”或“属于”关系,您可能应该使用
它将负责在单个事务中验证和保存所有已发布的模型数据。
If your models 1-3 have "has many" or "belongs to" relationships, you should probably use
It will take care of validating and saving all posted model-data in a single transaction.
是的,你可以。
另请参阅手册。
Yes, you can.
Also take a look at the manual.
如果它们相关,最好的方法是 Model::saveAll()。
如果你不能使用 saveAll() 因为你需要使用 Model::query() 之类的东西,你可以这样做:
从 Cake 1.3 开始,运行 begin 时使用什么模型实际上并不重要/提交/回滚语句;它们都会导致执行相同的代码,并且没有任何特定于模型的副作用。
The most preferable method is Model::saveAll(), if they are related.
If you can't use saveAll() becuase you need to use something such as Model::query(), you can do:
As of Cake 1.3, it doesn't actually matter what model you're using when you run the begin/commit/rollback statements; they all cause the same code to execute and don't have any model-specific side effects.