1撮胧、原生MySQL
// 開啟一個事務
mysql_query('START TRANSACTION');
$res1 = mysql_query(update table set money=money-1 where id =)
$res2 = mysql_query(update table set money=money+1 where id =)
if($res1 && $res2){
// 成功之后提交
mysql_query('COMMIT');
}else{
// 失敗之后回滾
mysql_query('ROLLBACK');
}
2、Laravel5.4
DB::beginTransaction();
try{
// 業(yè)務處理和事務提交
$data['name'] = 'test_name';
$data['age'] = 25;
$getGroupId = DB::table('db_name.table_name1')->insertGetId($data);
foreach($list_data as $v) {
DB::table('db_name.table_name2')->insert([
'group_id' => $getGroupId,
'name' => $v['name']
]);
}
// 成功之后提交
DB::commit();
} catch (\Exception $exception) {
// 接收異常處理并回滾和拋出異常
DB::rollBack();
throw new \Exception('操作失斃锨獭芹啥!');
}
3、Yii2
// 開啟事務
$transaction = Yii::$app->db->beginTransaction();
try {
// 插入文章
$res = $this->save();
$data = [];
foreach ($category_ids as $val) {
$data[] = [$this->id, $val];
}
// 添加或更改分類文章時铺峭,先清空
CategoryArticle::deleteAll('post_id = :post_id ', [':post_id' => $this->id]);
// 批量插入分類文章表
Yii::$app->db->createCommand()->batchInsert('feehi_category_article', ['post_id','category_id'], $data)->execute();
// 提交
$transaction->commit();
} catch (\Exception $e) {
// 回滾
$transaction->rollback();
// 拋出異常
throw $e;
}
4墓怀、ThinkPHP3.2
$modelRefund = D('Home/OrderRefund');
$modelDetail = D('Home/OrderDetail');
// 啟動事務
$modelRefund->startTrans();
$refund_status = 1;
$updateRefundRes = $modelRefund->saveRefundStatus($where,$refund_status);
$status =6;
foreach($order_detail as $k => $v){
$where['id'] = $v;
$updateDetailRes = $modelDetail->saveDetailCompleteStatus($where,$status);
}
if($updateRefundRes && $updateDetailRes){
// 事務提交
$modelRefund->commit();
$this->success(C('OPERA_SUCCESS'));
}else{
// 事務回滾
$modelRefund->rollback();
$this->error(C('OPERA_FAILD'));
}