如何在Doctrine2中手动设置主键

jus*_*wes 7 symfony doctrine-orm

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

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

我使用它作为我的实体配置:

  type: entity
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
Run Code Online (Sandbox Code Playgroud)

我还在我的实体类中为id字段创建了一个setter.

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

什么是最好的解决方法或解决方案?

Léo*_*Lam 3

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


我存储了对 Connection 对象的引用,并使用它来手动插入行和更新关系。这完全避免了持久化和身份生成器。还可以使用 Connection 将所有这些工作包装在事务中。

执行插入语句后,您可以更新关系。

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

在你的初始化函数中:

  // Get the Connection
  $this->connection = $this->getContainer()->get('doctrine')->getEntityManager()->getConnection();
Run Code Online (Sandbox Code Playgroud)

在你的主体中:

  // 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);
  }
Run Code Online (Sandbox Code Playgroud)

创建这个函数:

  // 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);
  }
Run Code Online (Sandbox Code Playgroud)