Phalcon PDO 事务无法正常工作

Phalcon PDO transaction is not working correct

交易的问题解决了我将近一整天的时间,但还是失败了。 我的要求是在一次交易中在 table 主题和 table topic_data 中插入一条新记录。 我有这样的代码:

// database connection
$di->set( 'db', function() use( $conf ) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter( [
        'host' => $conf->db->host,
        'username' => $conf->db->username,
        'password' => $conf->db->password,
        'dbname' => $conf->db->dbname,
        'options' => [
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_PERSISTENT => true,
            \PDO::ATTR_AUTOCOMMIT => false
        ]
    ] ); 
} );

// transaction code
public function create( $params ) {
    $this->db->begin();

    $id = \Idalloc::next();
    $topic = new Topic();
    $topic->id = $id;
    $topic->ctime = $_SERVER[ 'REQUEST_TIME' ];

    $tags = $params[ 'tags' ];

    $params[ 'tags' ] = implode( ',', $tags );
    $topic->assign( $params );

    if( $topic->save() === false ) {
        $this->db->rollback();
        return false;
    }

    for( $i = 0, $l = count( $tags ); $i < $l; ++$i ) {
        $topicTag = new TopicTag();
        $topicTag->tag_id = $tags[ $i ];
        $topicTag->topic_id = $id;
        $topicTag->type = $params[ 'type' ];
        if( $topicTag->save() === false ) {
            $this->db->rollback();
            return false;
        }
    }

    var_dump( $this->db->isUnderTransaction() );

    $this->db->commit();
    return $id;
}

失败:

我该如何解决这个问题,是否有创建手动交易的简单方法?

我找到了这个问题的答案。 DI 中设置的 'db' 必须共享。所以需要另一个参数 "TRUE" :

// database connection
$di->set( 'db', function() use( $conf ) {
    return new \Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter( [
        'host' => $conf->db->host,
        'username' => $conf->db->username,
        'password' => $conf->db->password,
        'dbname' => $conf->db->dbname,
        'options' => [
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_PERSISTENT => true,
            \PDO::ATTR_AUTOCOMMIT => false
        ]
    ] ); 
}, true );