ThinkPHP5 事务使用方法
  • 日期2018-06-30
  • 评论 0
  • 阅读 1730
  • 分类 Thinkphp笔记
  • 字数 10
  • 收录 正在检测...

ThinkPHP5 事务使用方法

<?php
$success = true; //因为try catch中不能使用success和error返回结果,所以定义一个变量用于判断
/**
    * 知道success和error方法是怎么实现的吗?
    * 看源码的最后两行
    * $response&nbsp;=&nbsp;Response::create($result, $type)-&gt;header($header);
    * throw new HttpResponseException($response);
    * 没错,是用抛出异常的方式实现的
    * 而代码try正好捕获了该异常,所以代码永远只会走catch
    */
// 启动事务
Db::startTrans();
try {
    $this-&gt;dbName-&gt;insert($input);
    $lastId&nbsp;&nbsp;&nbsp;=&nbsp;$this->dbName->getLastInsID();
    $relation&nbsp;=&nbsp;Acms::make_relation($lastId, $roleIds, 'uid', 'group_id');
    Db::name("AuthRelation")->insertAll($relation);
    // 提交事务
    Db::commit();
} catch (Exception $e) {
    // 回滚事务
    Db::rollback();
    $success = false;
}
if ($success) {
    $this->success("新增管理员成功!");
} else {
    $this->error("新增管理员失败!");
}
?>

评论 (0)