Doctrine orm 如何在Doctrine2中手动设置主键

Doctrine orm 如何在Doctrine2中手动设置主键,doctrine-orm,symfony,Doctrine Orm,Symfony,我正在使用Doctrine2 ORM将数据导入一个新的Symfony2项目 所有新记录都应具有自动生成的主键。但是,对于导入,我希望保留现有的主键 我将此用作我的实体配置: type: entity id: id: type: integer generator: { strategy: AUTO } 我还为实体类中的id字段创建了一个setter 但是,当我将该实体持久化并刷新到数据库中时,我手动设置的密钥不会被保留 最好的解决方法是什么?您可能已经考

我正在使用Doctrine2 ORM将数据导入一个新的Symfony2项目

所有新记录都应具有自动生成的主键。但是,对于导入,我希望保留现有的主键

我将此用作我的实体配置:

  type: entity
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
我还为实体类中的id字段创建了一个setter

但是,当我将该实体持久化并刷新到数据库中时,我手动设置的密钥不会被保留


最好的解决方法是什么?

您可能已经考虑过这一点,但我的方法是将导入的生成器策略设置为“无”,以便您可以手动导入客户端代码中的现有id。然后,一旦导入完成,将生成器策略更改回“auto”,让RDBMS从那里接管。条件设置可以确定是否调用id设置器。祝你好运-让我们知道你最终决定使用什么。

以下答案不是我的,而是问题中发布的OP。我已将其移至此社区wiki答案中。


我存储了对连接对象的引用,并使用该引用手动插入行和更新关系。这完全避免了持久化器和标识生成器。也可以使用连接将所有这些工作打包到事务中

执行insert语句后,可以更新关系

这是一个很好的解决方案,因为它避免了在实时服务器上交换配置时可能遇到的任何潜在问题

在init函数中:

  // Get the Connection
  $this->connection = $this->getContainer()->get('doctrine')->getEntityManager()->getConnection();
  // Add a record to the database using Connection
  protected function addRecord($columns, $oldRecord)
  {
    // Insert data into Record table
    $record = array();
    foreach($columns as $key => $column)
    {
      $record[$column] = $oldRecord[$key];
    }
    $record['id'] = $record['rkey'];
    // Insert the data
    $this->connection->insert('Record', $record);
  }
在你的主体中:

  // Loop over my array of old data adding records
  $this->connection->beginTransaction();

  foreach(array_slice($records, 1) as $record)
  {
    $this->addRecord($records[0], $record);
  }

  try
  {
    $this->connection->commit();
  }
  catch(Exception $e)
  {
    $output->writeln($e->getMessage());
    $this->connection->rollBack();

    exit(1);
  }
创建此函数:

  // Get the Connection
  $this->connection = $this->getContainer()->get('doctrine')->getEntityManager()->getConnection();
  // Add a record to the database using Connection
  protected function addRecord($columns, $oldRecord)
  {
    // Insert data into Record table
    $record = array();
    foreach($columns as $key => $column)
    {
      $record[$column] = $oldRecord[$key];
    }
    $record['id'] = $record['rkey'];
    // Insert the data
    $this->connection->insert('Record', $record);
  }

谢谢你的提示。我一直在这样做,但我不确定它是否理想。我想我可能会执行原始的DQL查询。我的解决方案见上文。我将Connection对象用作PDO的一个令人愉快的接口。如何(暂时)禁用id生成器策略: