Tar*_*rek 33 php mysql transactions codeigniter codeigniter-3
我正在使用Codeigniter交易
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->trans_complete();
这工作得很好,我有问题是内部的trans_start和trans_complete我打电话等功能,这些功能与数据库交易,使他们包含插入和更新以及一些删除...例如:
$this->db->trans_start();
 $this->utils->insert_function($data);
 $this->utils->update_function2($test);
$this->db->trans_complete();
现在,如果执行这些函数并且发生一些错误,CodeIgniter将不会执行回滚.
处理此类问题的最佳方法是什么?
我想到的唯一解决方案是从这些函数返回错误并在那些函数内添加(trans_stat和trans_complete)如果它返回错误测试则执行$this->db->trans_rollback
例如:
    $this->db->trans_start();
     $result = $this->utils->insert_function($data);
     if($result === false){
       $this->db->trans_rollback();
     }
    $this->db->trans_complete();
有没有更好的方法呢?
更新1:
根据要求我正在调用的外部函数示例:
   // insert_function contains
    $rec = array(
        'numero' => $numero,
        'transaction_id' => $id,
        'debit' => $product_taxes['amount_without_taxes'],
        'date' => $data['date_transaction'],
    );
    $this->addExerciceAccountingRecords($rec);
  and addExerciceAccountingRecords contains
   function addExerciceAccountingRecords($records) {
    $this->db->insert('transactions_exercices', $records);
    }
Abd*_*lam 37
使用
transactions意味着支持数据库安全地插入数据.所以在Codeigniter中,我们在Model中编写每个与数据库相关的函数而不是在Controller中..在你的第二个代码(不工作)中你已经指出了模型.(utils).这么简单我敢肯定这不起作用.因为它不是与模型和Controller并行的插入数据.交易应该在模型中编码(我将在我的答案中写入模型).
加载这些东西
假设
在您的代码中,您使用了$data和$test作为数组.所以我假设有两个数组用于插入和更新数据.
你的数据集
$data = array(
   'title' => 'My title' ,
   'name' => 'My Name' ,
   'date' => 'My date'
);
$id = 007;
$test = array(
   'title' => $title,
   'name' => $name,
   'date' => $date
);
你的守则
$this->db->trans_start(); # Starting Transaction
$this->db->trans_strict(FALSE); # See Note 01. If you wish can remove as well 
$this->db->insert('table_name', $data); # Inserting data
# Updating data
$this->db->where('id', $id);
$this->db->update('table_name', $test); 
$this->db->trans_complete(); # Completing transaction
/*Optional*/
if ($this->db->trans_status() === FALSE) {
    # Something went wrong.
    $this->db->trans_rollback();
    return FALSE;
} 
else {
    # Everything is Perfect. 
    # Committing data to the database.
    $this->db->trans_commit();
    return TRUE;
}
笔记
小智 5
我尝试的更多是技巧,但这对我有用。
$this->db->trans_begin();
  $rst1=  $this->utils->insert_function($data);
  $rst2 =  $this->utils->update_function2($test);
if($this->db->trans_status() === FALSE || !isset($rst1) || !isset($rst2)){
   $this->db->trans_rollback();
}else{
   $this->db->trans_commit();
}
| 归档时间: | 
 | 
| 查看次数: | 38456 次 | 
| 最近记录: |