在Postgres数据库中导入具有手动设置的ID的数据

时间:2018-10-09 10:50:39

标签: php postgresql symfony

我最近编写了一个导出脚本,用于从JSON数据更新数据库。 我想保留旧的身份证,然后遇到两个问题:

1)即使表已被删除或截断,Postgres也会跟踪最后插入的id 2)当使用setId()方法在实体上手动设置id时,它将被忽略并使用下一个可用的id

这是我想出的解决方案,我想分享一下

1 个答案:

答案 0 :(得分:0)

<?php

// Deleting old datas
foreach ($oldEntities as $entity) {
    $em->remove($entity);
}

$em->flush();

// Fetching the table name from the entity class
$tableName = $em->getClassMetadata(YourEntity::class)->getTableName();
// Resetting table ids sequence to 1
$em->getConnection()->exec('ALTER SEQUENCE ' . $tableName . '_id_seq RESTART WITH 1');

// Disabling auto-increment for the table
// This is necessary because otherwise a manually set id will be ignored
$metadata = $em->getClassMetaData(YourEntity::class);
$metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

// Importing your datas
foreach ($exportedJSONdatas as $row) {
    $entity = new YourEntity();

    $entity
        ->setId($row->id)
        ->setTitle($row->title)
        // ... set whatever else you want
    ;

    $em->persist($entity);
}

$em->flush();

// Setting the id that will be used when new data is persisted
// Otherwise Postgres will try to insert with id 1 and fail
$em->getConnection()->exec(
    'SELECT SETVAL(
        \'' . $tableName . '_id_seq\', 
        (SELECT MAX(id) + 1 FROM ' . $tableName . ')
    )'
);

// You're good to go, new persisted entities will continue with the right id