墨文院 发文

tp6/thinkphp6事务操作

+关注 逍遥涛子

最简单的方式是使用 transaction 方法操作数据库事务,当闭包中的代码发生异常会自动回滚,例如:

Db::transaction(function () {
    Db::table('think_user')->find(1);
    Db::table('think_user')->delete(1);
});

也可以手动控制事务,例如:

// 启动事务
Db::startTrans();
try {
    Db::table('think_user')->find(1);
    Db::table('think_user')->delete(1);
    // 提交事务
    Db::commit();
} catch (\Exception $e) {
    // 回滚事务
    Db::rollback();
}
Db::transactionXa(function () {
    Db::connect('db1')->table('think_user')->delete(1);
    Db::connect('db2')->table('think_user')->delete(1);
}, [Db::connect('db1'),Db::connect('db2')]);
<?php
use think\facade\Db;    //有多少人不带这个就开始的???
// 启动事务
Db::startTrans();
try {
    $uid = Comment::where('id',input('id'))->value('uid');//查会员ID
    if (!$uid) {
        throw new \Exception('未查到会员UID');
    }
    $u_data = U::where(['id'=>$uid])->save(['comment'=>1]);//会员限评
    if (!$u_data) {
        throw new \Exception('禁止会员评论失败');
    }
    $c_data = Comment::where(['id'=>input('id')])->save(['status'=>0]);
    if (!$c_data) {
        throw new \Exception('禁止评论展示失败');
    }
    // 提交事务
    Db::commit();
    return $this->success('封禁评论及会员评论功能成功');
} catch (\Exception $e) {
    // 回滚事务
    Db::rollback();
    return $this->fail($e->getMessage());
}
?>

如果抛出致命错误: Class 'app\api\validate\Exception' not found

请注意:throw new \Exception 或者 throw new \think\Exception   有没有在Exception前边带上\杠

我要反馈

本文链接:http://www.71us.com/p/1618294845542.html
下一篇:《山河令》龚俊和张哲瀚之间的竞争关系,网友:海浪钉上头