开发者社区> 问答> 正文

Codeigniter交易?mysql

我正在使用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); }

展开
收起
保持可爱mmm 2020-05-17 21:32:12 1115 0
1 条回答
写回答
取消 提交回答
  • 使用transactions手段支持数据库安全地插入数据。因此,在Codeigniter中,我们在Model中而不是Controller中编写与数据库相关的所有功能。。在您的第二个代码(不起作用)中,您已经在上面指向了模型utils。如此简单,我确定这将无法正常工作。因为它不是与模型和控制器并行的插入数据。交易应在模型中编码(我将在回答中用模型编写)。

    加载这些东西

    数据库库 型号类别 URL助手 届会 假设条件

    在您的代码中,您已使用$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; } 笔记

    默认情况下,Codeigniter在严格模式下运行所有​​事务。当 被严格模式启用,如果你正在运行的交易多组,如果一组发生故障,所有组将被回滚。如果禁用了严格模式,则每个组将被独立对待,这意味着一个组的故障不会影响其他任何组。来源:stack overflow

    2020-05-17 21:42:22
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
搭建电商项目架构连接MySQL 立即下载
搭建4层电商项目架构,实战连接MySQL 立即下载
PolarDB MySQL引擎重磅功能及产品能力盛大发布 立即下载

相关镜像