本文概述
在执行诸如插入/删除/更新/回滚之类的操作之后, 模型事务有助于维护数据库的完整性。事务在提交数据库之前检查操作是否成功完成。
交易分为3种类型:
- 手动交易
- 隐式交易
- 孤立交易
手动交易
仅存在一个连接且易于交易时使用此方法。可以通过仅将当前连接移到事务模式来创建该事务, 然后不管该操作是否成功提交或回滚该操作。
实作
<?php
use 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 transaction
if ($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 transaction
if ($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, 虚拟外键检查和业务规则均与主连接隔离。
实作
<?php
use 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();
}
评论前必须登录!
注册