MySQL Codeigniter:我可以在控制器函数中使用 $this->db->trans_start() 和 trans_complete 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23782230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:32:47  来源:igfitidea点击:

Codeigniter: Can I use $this->db->trans_start() and trans_complete with in my controller function?

mysqlsqlcodeigniteractiverecord

提问by Syed Sajid

I have more than one model functions that are executed before transaction is completed. For example

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

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

what is the best way to use trans_start() and trans_complete() so incase the process of insert or update is interrupted at any point the transaction can be rollback or committed accordingly...

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

Is there any possibility I can use these below lines in my controller? Like this?

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

$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();

Is it a good practice if not what is the best way to handle such transactions?

如果不是,处理此类交易的最佳方法是什么,这是一种好习惯吗?

回答by websterridge

Your first alternative is proper.

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

Transaction logic is at the database level. Codeigniter does not document doing it at the 'table' level ( see http://www.codeigniter.com/user_guide/database/transactions.html).

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

Your second alternative does not make sense - the transaction encompasses different tables.

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

回答by MrTomTom

I the mentioned approach the best/will work from within a model. In my case I have delete something and then run some SQL to recalculate the totals which a stored in another table. So something like the following in the model is a good approach?

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

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

I'd prefer to have them both in the same function in the model as the delete can be called from a couple of controllers.

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