保存多个记录,并获取每个记录的id

rsl1atfo  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(359)

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

public function saveAdditionalDataForRecord($header, $data, $record)
    {
        $em = $this->getEntityManager();
        foreach ($header as $key => $value) {
            $clientRecordAdditionalData  = new ClientRecordAdditionalData();
            $clientRecordAdditionalData->setName($value);
            $clientRecordAdditionalData->setValue($data[$key]);
            $clientRecordAdditionalData->setRecord($record);
            $em->persist($clientRecordAdditionalData);
        }
        $em->flush();
        return $clientRecordAdditionalData->getId();

    }

我想返回id为saved records的数组,而不是上次保存的记录。我该怎么做?我将非常感谢您的帮助;)致以最诚挚的问候

a6b3iqyw

a6b3iqyw1#

只有两种方法可以做到这一点:要么使用插入前生成的非亮片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);
}
gcmastyq

gcmastyq2#

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;

}

相关问题