bes*_*rld 5 activerecord transactions codeigniter
禁用交易有什么意义? http://ellislab.com/codeigniter/user-guide/database/transactions.html
$this->db->trans_off()
Run Code Online (Sandbox Code Playgroud)
我看不出用法.是用于测试目的吗?
"当禁用事务时,您的查询将自动提交,就像在没有事务的情况下运行查询时一样."
我有一个表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();
Run Code Online (Sandbox Code Playgroud)
但它被回滚(没有插入任何内容),因为nameOfUser2第二个插入中不存在列列.
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();
Run Code Online (Sandbox Code Playgroud)
上面会将testCVVCOOL字符串插入-table,user即使第二个插入中有错误($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();
Run Code Online (Sandbox Code Playgroud)
-
//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();
Run Code Online (Sandbox Code Playgroud)