禁用事务(在ActiveRecord CodeIgniter中)有什么意义?



禁用事务有什么意义? http://ellislab.com/codeigniter/user-guide/database/transactions.html

$this->db->trans_off()

我看不到使用情况。是出于测试目的吗?

"当事务被禁用时,您的查询将自动提交,就像在没有事务的情况下运行查询时一样。

我有一个名为user的表,其中存在一列nameOfUser.nameOfUser2- 列不存在

TEST1此代码将尝试使用正常事务执行 2 次插入:

$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
$this->db->trans_complete();    

但它被回滚了(没有插入任何内容),因为第二个插入中不存在nameOfUser2-column 列。

TEST2此代码将尝试在禁用事务的情况下执行 2 次插入

$this->db->trans_off();
$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
$this->db->trans_complete();    

上面会将testCVVCOOL字符串插入user-table,即使第二个插入中存在错误($this->db->insert('user', array('nameOfUser2' => 'test2'));)

您什么时候需要以这种方式禁用交易?

您什么时候需要以这种方式禁用事务?

我的理解是,如果出现问题,事务不允许在同一线程中进行更多交互(如您的第一个示例)。因此,如果您想在提交之前和回滚之前在数据库中执行其他操作,您将无法做到。

伪示例:

//will not work
$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
//more likely this would be a condition that makes sense 
//perhaps using a query result from earlier in function
if(1===1){
$this->db->query('INSERT INTO errors (db) values (1)');//nogo
}
$this->db->trans_complete(); 

-

//will work
$this->db->trans_off();
$this->db->trans_start();
$this->db->insert('user', array('nameOfUser' => 'testCVVCOOL'));
$this->db->insert('user', array('nameOfUser2' => 'test2'));
//more likely this would be a condition that makes sense 
//perhaps using a query result from earlier in function
if(1===1){
$this->db->query('INSERT INTO errors (db) values (1)');//OK
}
$this->db->trans_complete(); 

这完全取决于我们使用事务的场景 -

当需要交易时:

需要一组整体操作,即如果有人在线订购产品,并且订单确认涉及一些步骤,那么如果任何步骤失败,则还原整个订单交易。

当需要关闭事务时:

如果我正在尝试一些任何类型的信息对我来说都值得的东西。然后我们可以使用交易关闭功能。无论发生什么错误,请保存符合条件的数据。

最新更新