thinkphp's Db transaction, delete example

  1. First, delete the method class, in QuestionController, the method is as follows

    //删除题目
    public function del()
    {
        if ( $this->id < 0) {
            return $this->do_error("请选择要删除题目");
        }
        if (is_array($this->id)) {
            if (sizeof($this->id) == 0) {
                return $this->do_error('请选择需要删除的数据');
            }    
        }
        $questionList = Question::with('questionAnswer')->select($this->id);
        if(!$questionList){
            return $this->do_error('id有误');
        }   
        $question = new Question();   
        $result = $question->deleteQuestionAndAnswer($questionList);
        if ($result) {
            return $this->do_success();
        }
        return $this->do_error('删除失败');
    }
  • deleteQuestionAndAnswer is the actual deletion method. In the Question class, questionAnswer is the answer to the question. There may be more than one. The relationship with Question is one-to-many. One Question corresponds to multiple QuestionAnswers . The QuestionAnswer is also deleted, if a deletion fails, it will be rolled back

  1. Secondly, deleteQuestionAndAnswer is on the Question class, the method is as follows

public function deleteQuestionAndAnswer($questionList) {
    //启动事务
    Db::startTrans();
    try {
       foreach ($questionList as $item){
            $answerList = $item['questionAnswer'];
            $result = Db::table("question")->delete($item['id']);
            if(!$result){
                throw new Exception("删除题目失败");
            }
            foreach ($answerList as $k => $row){   
                $result = Db::table("question_answer")->delete($row['id']);
                if(!$result){
                    throw new Exception("删除题目失败");
                }
            }
        }
        // 提交事务
        Db::commit();
    } catch (\Exception $e){
        echo($e);
        exit();
        // 事务回滚
        Db::rollback();
        return false;
    }
    return true;
}
  • Db::startTrans(); start a transaction

  • $result = Db::table("question")->delete($item['id']); Delete questions one by one by id

  • $result = Db::table("question_answer")->delete($row['id']); Delete the answers corresponding to each question by id

  • Db::commit(); Commit the transaction when there is no problem

  • Db::rollback(); If there is a problem or exception, roll back when catching

Guess you like

Origin blog.csdn.net/weixin_36667844/article/details/128971774