Can I rollback a transaction after commiting it with Datamapper/Codeigniter?

☆樱花仙子☆ 提交于 2019-12-13 02:36:23

问题


Is it possible to rollback a transaction after it has been commited? I ask this because in the Datamapper documentation i see the trans_begin() method, but i didn't find the trans_end() method. Codeigniter has the trans_complete() method, so i assumed Datamapper might have a similar method.

One thing I found interesting is this answer. Is there anything similar to a savepoint in Datamapper/Codeigniter?


回答1:


http://datamapper.wanwizard.eu/pages/transactions.html

DataMapper handles transactions in very much the same way that CodeIgniter does (read CodeIgniter Transactions), obviously because it uses the same methods! The only real difference is that you'll be calling the transaction methods directly on your DataMapper objects.

This means that instead of:

$this->db->trans_begin();

You'd use:

$my_datamapper_object->trans_begin();

Everything else, according to the Datamapper documentation, is identical to Codeigniter in regards to transactions. If you look at the source code for the Datamapper library, you'll see that all trans_*() calls are simply wrapper functions. Example:

// Datamapper.php 1.8.dev line 3975
/**
 * Trans Complete
 *
 * Complete a transaction.
 *
 * @return  bool Success or Failure
 */
public function trans_complete()
{
    return $this->db->trans_complete();
}

A trans_end() method does not exist in either Codeigniter or Datamapper. You'd use trans_start() and trans_complete() for automatic transactions, or to call them manually:

http://codeigniter.com/user_guide/database/transactions.html

Running Transactions Manually

If you would like to run transactions manually you can do so as follows:

$this->db->trans_begin();

$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');

if ($this->db->trans_status() === FALSE)
{
    $this->db->trans_rollback();
}
else
{
    $this->db->trans_commit();
}

Just replace $this->db with your Datamapper object. For example.

$u = new User($id);
$u->trans_begin();
$u->name = 'Jorge';
$u->save();

if ($u->trans_status() === FALSE)
{
    $u->trans_rollback();
}
else
{
    $u->trans_commit();
}


来源:https://stackoverflow.com/questions/7208439/can-i-rollback-a-transaction-after-commiting-it-with-datamapper-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!