代码之家  ›  专栏  ›  技术社区  ›  Magnesium

导入Postgres数据库中手动设置id的数据

  •  0
  • Magnesium  · 技术社区  · 6 年前

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

    2) 当使用setId()方法手动设置实体的id时,它将被忽略并使用下一个可用的id

    1 回复  |  直到 6 年前
        1
  •  0
  •   Magnesium    6 年前
    <?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