How to manually set the primary key in Doctrine2

I am importing data into a new Symfony2 project using Doctrine2 ORM.

All new entries must have an automatically generated primary key. However, for my import, I would like to keep the existing primary keys.

I use this as my Entity configuration:

type: entity id: id: type: integer generator: { strategy: AUTO } 

I also created a setter for the id field in the entity class.

However, when I save and hide this object in the database, the key that I manually set is not saved.

What is the best solution or solution for this?

+7
source share
2 answers

The following answer is not mine, but OP, which was published in the question. I moved it to this community wiki answer.


I saved the link to the Connection object and used this to manually insert rows and update relationships. This avoids constant and identical generators. It is also possible to use a connection to transfer all this work into a transaction.

After you execute insert statements, you can update the relationship.

This is a good solution because it avoids any potential problems that may arise when replacing your configuration on a real server.

In your init function:

  // Get the Connection $this->connection = $this->getContainer()->get('doctrine')->getEntityManager()->getConnection(); 

In your main body:

  // 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); } 

Create this function:

  // 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); } 
+3
source

You probably already considered this, but my approach was to set the generator to a no import strategy so that you could manually import the existing identifier into your client code. Then, once the import is complete, change the generator strategy to β€œauto” to allow RDBMS to go from there. The condition may determine if the identifier is being called. Good luck - let us know what you ultimately decided to use.

+3
source

All Articles