dqyhj2014 2013-11-13 21:00
浏览 60

Phalcon \ Mvc \ Model - 回滚失败的交易

The code:

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

My question is - what happens if along the way, between beforeSave() and afterSave() there's an Exception thrown - how can I cleanly roll back the transaction? Where should I stick $this->getDi()->getShared('db')->rollback(); in to?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongnao6858 2013-11-14 07:53
    关注

    I'd recommend overloading the save() method entirely.

    Here's my example with transactions. Note that you won't need transactions if you're not going to implement additional logic here (like removing related models)

    /**
     * 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;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突