Codeigniter Try Catch 交易

Codeigniter Try Catch Transaction

我有这个事务和 try catch 语句检查每个 $_POST['count'] 的值不小于 0。*回滚仅在 if 语句为假时发生,它不包括过去的更新不正确

$this->db->trans_begin();
foreach($_POST['ID'] as $val => $r)
{

        //Gets Count            
        $this->db->select('count');
        $this->db->from('table1');
        $this->db->where('table_id', $r);
        $oc = $this->db->get()->row('count');
        $nc = (($oc) - $_POST['count'][$val]);

        //Gets Total
        $this->db->select('cost');
        $this->db->from('table1');
        $this->db->where('table_id', $r);
        $ot = $this->db->get()->row('cost');
        $total = ($ot + $total);
        try{
            if($nc > 0){
                //Updates Quantity  
                $process = array(
                    'current_count' => $nc,
                );

                $this->db->where('product_id', $rm);
                $this->db->update('products', $process);
            }
        }
        catch(Exception $e){
            $this->db->trans_rollback();
            $this->session->set_flashdata('error','Production Failed. 1 or more Raw Materials required for production is insufficient.');
            exit;
        }
}
$this->db->trans_commit();

之后有插入和更新语句,但我想要的是在捕获到异常时停止整个过程,显然 exit; 语句没有这样做

有多种方法可以做到这一点。也许最简单的就是这个。

型号:

//I'm making the function up cause you don't show it
public function do_something(){ 

//all code the same up to here...

if($nc > 0){
    //Updates Count
    $process = array('count' => $nc);

    $this->db->where('table_id', $r);
    $this->db->update('table1', $process);
 } else {
     $this->db->trans_rollback();
     throw new Exception('Model whats_its_name has nothing to process');
 }

模型中的 catch 语句将捕获数据库 class(es) 可能抛出的任何异常。 (他们会抛出任何异常吗?我不知道。)

控制器

try{
    $this->some_model->do_something();
}
catch (Exception $e) {
 //catch the exception thrown in do_something()
 //additional handling here
}

综上所述,在调用 $this->some_model->do_something();

之前检查 $_POST['count'] 的适当值可能是明智的