2

编码:

class myModel extends Phalcon\Mvc\Model
{
    public function beforeSave()
    {
        $this->getDi()->getShared('db')->begin();
    }
    ...
    public function afterSave()
    {
        $this->getDi()->getShared('db')->commit();
    }
}

我的问题是——如果在此过程中,在beforeSave()afterSave()之间抛出了一个异常——我怎样才能干净地回滚事务?我应该在哪里坚持$this->getDi()->getShared('db')->rollback(); 进入?

谢谢!

4

1 回答 1

3

我建议完全重载 save() 方法。

这是我的交易示例。请注意,如果您不打算在此处实现其他逻辑(例如删除相关模型),则不需要事务

/**
 * Delete old relations before saving new ones
 */
public function save($data=null, $whiteList=null)
{
    $db = $this->getDI()->get('db');

    try
    {
        // Start transaction
        $db->begin();

        // ... Do some additional work. Remove related models etc...

        // Update model
        if (!parent::save($data, $whiteList))
            throw new \Exception('Cannot save the model');

        $db->commit();
    }
    catch (\Exception $e)
    {
        $db->rollback();

        $this->appendMessage(new \Phalcon\Mvc\Model\Message($e->getMessage(), '', 'error', $this));
        return false;
    }
    return true;
}
于 2013-11-14T07:53:45.090 回答