Symfony2 / Doctrine - 获取即将插入的行的id

时间:2014-03-27 06:06:44

标签: php symfony doctrine-orm

这是我的代码:

$cost = new Cost();

if(some_condition){
    $cost->setColumn1('some_value');
} else if(some_condition){
    $cost->setColumn2('some_value');

    /**How do I get the ID of the cost row that is about to be inserted here**/

} else if(some_condition){
    $cost->setColumn3('some_value');
}

$em->persist($cost);
$em->flush();

我想过这样做:

    $cost = new Cost();

    if(some_condition){
        $cost->setColumn1('some_value');
    } else if(some_condition){
        $cost->setColumn2('some_value');
        $em->persist($cost);
        $em->flush();

        /**How do I get the ID of the cost row that is about to be inserted here**/
        $cost->getId();

    } else if(some_condition){
        $cost->setColumn3('some_value');
    }

    $em->persist($cost);
    $em->flush();

但是由于$ cost对象被持久化并刷新两次,所以不会将该行插入两次吗?我该如何解决这个问题?有更聪明的方法吗?

2 个答案:

答案 0 :(得分:0)

试试这个并解决了你的问题

$cost = new Cost();

if(some_condition){
    $cost->setColumn1('some_value');
    $em->persist($cost);
} else if(some_condition){
    $cost->setColumn2('some_value');
    $em->persist($cost);
    /**How do I get the ID of the cost row that is about to be inserted here**/
    $cost->getId();

} else if(some_condition){
    $cost->setColumn3('some_value');
    $em->persist($cost);
}
$em->flush();

答案 1 :(得分:0)

您显示的第二个示例代码很好,只需从最后删除$ em-> persist($ cost)调用,您只需要保留一次。 Doctrine很聪明,可以在第二次刷新时弄清楚$ cost实体已经被持久化了一次,它只会更新已更改的字段(在你的情况下是column3)。

你可以更进一步,你可以将$ cost传递给第一次刷新,所以使用$ em-> flush($ cost),它只会刷新那个对象,而不是其他对象。其他对象将在最后的冲洗呼叫中处理。