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条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法