琯琯博客 纸上得来终觉浅,绝知此事要躬行。

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

琯琯
2018-02-28

一、原生 MySQL

<?php
// 开启一个事务
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');   
}

二、Laravel5.4

<?php
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('操作失败!');
}

三、Yii2

<?php
// 开启事务
$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;
}

四、ThinkPHP3.2

<?php
$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'));
}

(完)


相关文章

评论

内容导航