如何在symfony2中获取批量刷新的插入ID

时间:2016-05-05 09:27:39

标签: php symfony doctrine-orm

如何从批量插入数据中获取所有插入ID? 我的代码如下:

 foreach ($urls as $url) {
        $subDocument = new SubDocument();
        $subDocument->setUrl($url);
        $subDocument->setParentDocument($parentDocument);
        $dm->persist($subDocument);
    }
    $dm->flush();
    $dm->clear();

现在我怎样才能获得那些插入ID记录?

1 个答案:

答案 0 :(得分:1)

您可以在Subdocument之后访问$dm->flush();的ID,因此您必须保留Subdocument个实例以在刷新后检索其ID。

 $subDocuments = array(); // init array
 foreach ($urls as $url) {
    $subDocument = new SubDocument();
    $subDocument->setUrl($url);
    $subDocument->setParentDocument($parentDocument);
    $subDocuments[] = $subDocument; //added to array
    $dm->persist($subDocument);
}
$dm->flush();
//now you can access IDs iterating $subDocuments like:
foreach($subDocuments as $subDocument) {
    echo $subDocument->getId();
}