首先上删除的方法类,在QuestionController,方法如下
//删除题目
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是真正实现的删除方法在Question这个类中,questionAnswer是题目的答案,可能有多个,和Question的关系是一对多,一个Question对应多个QuestionAnswer,要做的是把Question删除,相对应的QuestionAnswer也删除,一个删除失败都要回滚
其次deleteQuestionAndAnswer在Question类上,方法如下
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();开启事务
$result = Db::table("question")->delete($item['id']);按id一个个问题删除
$result = Db::table("question_answer")->delete($row['id']);按id一个个问题对应的答案删除
Db::commit();没问题时候提交事务
Db::rollback();有问题或者异常,在捕获时候回滚