📅  最后修改于: 2021-01-07 09:30:56             🧑  作者: Mango
在执行诸如插入/删除/更新/回滚之类的操作之后,模型事务有助于维护数据库的完整性。事务在提交数据库之前检查操作是否成功完成。
交易分为3种类型:
只有一个连接且易于交易时使用此方法。可以通过仅将当前连接移至事务模式来创建该事务,然后不管该操作是否成功提交或回滚该操作。
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();
}
}
输出:
隐式事务可确保正确存储数据。
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,虚拟外键检查和业务规则均与主连接隔离。
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();
}