douju6542 2016-09-22 12:02
浏览 35
已采纳

是否可以在CodeIgniter中回滚函数操作

Suppose i wan't to insert Data into 2 different tables, in codeigniter,

for example :

  • Insert into UserProfile table: name , mail to (get an id and use it in the next table)

  • Insert Employees table : UserProfile_id, shifts , position.

Up to now, all is working good, what can i do if i want to commit the action only if both insertions are commited...how can i rollback in case the first insertion went well and i don't want an empty profile.... My problem is that once the first insertion is committed ,suppose something went wrong in the next insertion - i get data to one table... any ideas?

  • 写回答

2条回答 默认 最新

  • dswfyq6201 2016-09-22 12:07
    关注

    See Transactions in codeigniter.

    Syntax(Given in Document as well):

    $this->db->trans_begin();
    
    $this->db->query('AN SQL QUERY...');
    $this->db->query('ANOTHER QUERY...');
    $this->db->query('AND YET ANOTHER QUERY...');
    
    if ($this->db->trans_status() === FALSE)
    {
            $this->db->trans_rollback();
    }
    else
    {
            $this->db->trans_commit();
    }
    

    Make sure to use $this->db->trans_begin() when running manual transactions, NOT $this->db->trans_start().

    Also see strict-mode.

    UPDATED

    For multiple models you can us this approach(my opinion), Not sure if its the only/best one:

    // MODEL_x
    
    public function functionX($data)
    {
        return  $this->db->insert('table_x',$data);
    }
    // MODEL_y
    
    public function functionY($data)
    {
        return  $this->db->insert('table_y',$data);
    }
    
    //controller
    $this->db->trans_start();
    $this->model_x->functionX();
    $this->model_y->functionY();
    $this->db->trans_complete();
    if ($this->db->trans_status() === FALSE) {
      //log error  
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料