原生PHP、Laravel5.4、Yii2和ThinkPHP3.2中的事务实例

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{
    // 业务处理和事务提交
    $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'));
}

你可能感兴趣的:(原生PHP、Laravel5.4、Yii2和ThinkPHP3.2中的事务实例)