使用doctrine保存多个记录并获取每个记录的id

时间:2018-01-09 13:09:13

标签: php mysql symfony doctrine-orm

我在php应用程序中有一个函数来保存表中的数据:

df <- rbind(c("Hello", "Once", "Hi"), c("World", "More", "Data"), c(4,21,23))
df <- as.data.frame(t(df))
write.csv(df,"test.csv", row.names = FALSE, quote = c(1,2))

我希望返回包含id保存记录的数组,而不是最后保存的记录。我怎样才能做到这一点?我会很乐意帮忙;) 最好的问候

2 个答案:

答案 0 :(得分:1)

public function saveAdditionalDataForRecord($header, $data, $record)
{
    $em = $this->getEntityManager();

    $ids = array();
    $objects = array();

    foreach ($header as $key => $value) {
        $clientRecordAdditionalData  = new ClientRecordAdditionalData();
        $clientRecordAdditionalData->setName($value);
        $clientRecordAdditionalData->setValue($data[$key]);
        $clientRecordAdditionalData->setRecord($record);
        $em->persist($clientRecordAdditionalData);

        $objects[] = $clientRecordAdditionalData;
    }

    $em->flush();

    foreach($objects as $object)
    {
        $ids[] = $object->id;
    }

    return $ids;

}

答案 1 :(得分:0)

只有两种方法可以执行此操作:使用在插入之前生成的非亮片ID(UUID)或在每次插入(刷新)之后检索最后一个插入ID。

安装ramsey/uuid以生成uuid。

foreach ($header as $key => $value) {
    $clientRecordAdditionalData  = new ClientRecordAdditionalData();
    $clientRecordAdditionalData->setId(Uuid::uuid4());
    $clientRecordAdditionalData->setName($value);
    $clientRecordAdditionalData->setValue($data[$key]);
    $clientRecordAdditionalData->setRecord($record);
    $em->persist($clientRecordAdditionalData);
}