本文概述
- 隐式交易
- 孤立交易
【Phalcon模型事务】交易分为3种类型:
- 手动交易
- 隐式交易
- 孤立交易
仅存在一个连接且易于交易时使用此方法。可以通过仅将当前连接移到事务模式来创建该事务, 然后不管该操作是否成功提交或回滚该操作。
实作
<
?phpuse Phalcon\Mvc\Controller;
class Cars extends Controller{public function saveAction(){// Start a transaction$this->
db->
begin();
$cars = new Cars();
$car->
name= 'Gallardo';
$car->
created_at = date('Y-m-d');
// The model failed to save, so rollback the transactionif ($car->
save() === false) {$this->
db->
rollback();
return;
}$carprice= new CarPrice();
$carprice ->
car_id = $car->
id;
$ carprice ->
type= 'head';
// The model failed to save, so rollback the transactionif ($carprice ->
save() === false) {$this->
db->
rollback();
return;
}// Commit the transaction$this->
db->
commit();
}}
输出
文章图片
隐式交易 隐式事务可确保正确存储数据。
实作
<
?php$carprice = new CarPrice();
$carprice->
type = 'head';
$car = new Cars();
$car->
name= 'Gallardo';
$car->
created_at = date('Y-m-d');
$car->
carprice= $carprice;
// Creates an implicit transaction to store both records$car->
save();
孤立交易 隔离的事务在新的连接中执行, 以确保所有生成的SQL, 虚拟外键检查和业务规则均与主连接隔离。
实作
<
?phpuse Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
try {// Create a transaction manager$manager = new TxManager();
// Request a transaction$transaction = $manager->
get();
$car = new Car();
$car->
setTransaction($transaction);
$car->
name= 'Gallardo';
$car->
created_at = date('Y-m-d');
if ($car->
save() === false) {$transaction->
rollback('Cannot save car?);
}$carprice = new CarPrice();
$carprice->
setTransaction($transaction);
$carprice->
car_id = $car->
id;
$carprice->
type= 'head';
if ($carprice->
save() === false) {$transaction->
rollback('Cannot save car price');
}$transaction->
commit();
} catch (TxFailed $e) {echo 'Failed, reason: ', $e->
getMessage();
}
推荐阅读
- Phalcon安全哈希
- Phalcon模型
- Phalcon模型行为
- Phalcon模型事件
- Phalcon国际化
- Phalcon日志
- 图文详细说明修好本地连接没有有效果的ip设置
- 图文详细说明打开img文件
- 图文详细说明输入法不显示在状态栏怎样办