一次

时间:2017-05-18 12:37:49

标签: mysql symfony doctrine-orm transactions flush

我做了很多搜索而没有成功。 我想了解这种情况下的flush()过程。

//Edit updateOptions
public function updateOptions($values){
    setOption('country',$values['country']);
    setOption('city',$values['city']);
    setOption('adress',$values['adress']);
    setOption('CP',$values['CP']);
    setOption('country_code',$values['country_code']);
}


function setOption($name, $value){

     $em = $this->getEntityManager('option.manager');

     $option = $this->getOption($name); //Entity Options
     $option->setValue($value);

     $em->persist($option);
     $em->flush();
}

当我查看mysql.log或分析器时,我发现了这个:

START TRANSACTION
UPDATE options SET value = 'France' WHERE name = 'country';
COMMIT
START TRANSACTION
SAVEPOINT DOCTRINE2_SAVEPOINT_2
UPDATE options SET value = 'Paris' WHERE name = 'city';
RELEASE SAVEPOINT DOCTRINE2_SAVEPOINT_2
SAVEPOINT DOCTRINE2_SAVEPOINT_2
UPDATE options SET value = 'Rue de Rivoli' WHERE name = 'adress';
RELEASE SAVEPOINT DOCTRINE2_SAVEPOINT_2
SAVEPOINT DOCTRINE2_SAVEPOINT_2
UPDATE options SET value = '75001' WHERE name = 'CP';
RELEASE SAVEPOINT DOCTRINE2_SAVEPOINT_2
SAVEPOINT DOCTRINE2_SAVEPOINT_2
UPDATE options SET value = '33' WHERE name = 'country_code';
RELEASE SAVEPOINT DOCTRINE2_SAVEPOINT_2
ROLLBACK

只有第一个更新/提交,我明白了,但我不明白为什么下一个会被回滚?

如果我在循环中使用setOption(),也会出现这种情况。

帮助会很棒。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

每次都不要调用persist()和flush()。我认为这可能是原因。由于您没有明确告诉EM开始交易,它可能会尝试通过persist()flush()

的组合来猜测它

尝试以下:

扩展您的updateOptions方法

public function updateOptions ()
{
    $em = $this->getEntityManager( 'option.manager' );

    $em->gebinnTransaction();

    setOption( 'country', 'France' );
    setOption( 'city', 'Paris' );
    setOption( 'adress', 'Rue de Rivoli' );
    setOption( 'CP', '75001 ' );
    setOption( 'country_code', '33' );

    $em->flush(); //just notif EM there're records to UPDATE

    //$success = false; 

    try
    {
        $em->commit();
        //$success = true;
    }
    catch ( \Exception $ex )
    {
        $em->rollback();
        // my fav is followinn: in DEV re-throw exception so you can inspect all in symfony-debug-bar
        // in prod just additional emergency log (monolog + swiftmailer) so you get an email

        if( $this->get( 'kernel' )->getEnvironment() !== 'prod' )
        {
            throw $ex;
        }
        $this->get( 'logger' )->addEmergency( 'Oh nooo! Not again :/' );

    }

 //return $success;
}

function setOption($name, $value){

     $option = $this->getOption($name); //Entity Options
     $option->setValue($value);
}