【问题标题】:Codeigniter: Can I use $this->db->trans_start() and trans_complete with in my controller function?Codeigniter:我可以在我的控制器函数中使用 $this->db->trans_start() 和 trans_complete 吗?
【发布时间】:2014-07-10 00:56:21
【问题描述】:

我有多个模型函数在事务完成之前执行。例如

$this->model_A->insert('....');
$this->model_C->insert('....');
$this->model_D->insert('....');
$this->model_E->update('....');

使用 trans_start() 和 trans_complete() 的最佳方法是什么,以便插入或更新过程在任何时候中断,事务可以相应地回滚或提交...

有没有可能我可以在我的控制器中使用以下这些行?像这样?

$this->db->trans_start();

    $this->model_A->insert('....');
    $this->model_C->insert('....');
    $this->model_D->insert('....');
    $this->model_E->update('....');

$this->db->trans_complete();

OR

$this->model_A->trans_start();

    $this->model_A->insert('....');
    $this->model_C->insert('....');
    $this->model_D->insert('....');
    $this->model_E->update('....');

$this->model_A->trans_complete();

如果不是处理此类交易的最佳方式,这是否是一种好习惯?

【问题讨论】:

    标签: mysql sql codeigniter activerecord


    【解决方案1】:

    你的第一个选择是正确的。

    事务逻辑在数据库级别。 Codeigniter 没有记录在“表”级别执行此操作(请参阅http://www.codeigniter.com/user_guide/database/transactions.html)。

    您的第二种选择没有意义 - 事务包含不同的表。

    【讨论】:

    • 我正在使用 $this->db->trans_start();在控制器的第一个替代方案中,您认为这样做是正确的吗?
    • 是的 - 控制器具有“整个过程的观点”。 Codeigniter 允许多表模型,但我不认为它们是正确的,本着 MVC 的精神,在这个特定的示例中,除非不同的表确实是非常紧密链接的更新(或选择)的一部分。但是您的问题没有公开实际数据,因此很难说多表模型是否合适。我不喜欢他们。控制器是不同模型可以关联的地方,这使您的意图更加清晰。
    【解决方案2】:

    我提到的方法最好/将在模型中起作用。在我的情况下,我删除了一些东西,然后运行一些 SQL 来重新计算存储在另一个表中的总数。那么模型中类似以下的内容是一个好方法吗?

    $this->db->trans_start();
       $this->db->delete('table_name', $data);
       $this->another_model->recalculate_update_thing('....');
    $this->db->trans_complete();
    

    我希望它们都在模型中的同一个函数中,因为可以从几个控制器调用删除。

    【讨论】:

      猜你喜欢
      • 2013-01-19
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      相关资源
      最近更新 更多