0

im having a problem while inserting new record to the database in Symfony 4 using doctrine/oracle/oci8 driver. My entity configration with sequence id generation:

<id name="id" type="integer" column="ID">
        <generator strategy="SEQUENCE"/>
        <sequence-generator sequence-name="FILES_SEQ" allocation-size="10" initial-value="1"/>
</id>

That's how I insert new record to the database:

$file = new File();
$file->setFileName($fileParams['fileName']);
...

$this->getEntityManager()->persist($file);
$this->getEntityManager()->flush();

Record is persisted successfully, but the problem is when I try to get last insert ID by:

$file->getId();

then the ID returned is 1 less then one in the database. Is this some kind of caching problem?? I tried using getEntityManager()->refresh($file) but it doesn't work. Also when I'm invoking findAll() method, the value of ID is correct there.

1 Answers1

0

$file is the object that you send to your database. In your class I imagine that you have somthing like this in your File class:

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

So the object file has no Id set (as it is not part of the constructor). It is set when you flush it to your db. If you want to get this Id back in your logic you need to retrieve file from your db with something like:

$this
    ->getEntityManager()
    ->getRepository(File::class)
    ->findOneByFileName($file->getFileName());
Pierrick Rambaud
  • 1,726
  • 1
  • 20
  • 47
  • I'm trying to get the ID after: $this->getEntityManager()->flush(); which from my understanding should be possible because the record is already persisted in the database and the ID is already generated. And its not empty, it's just one less than the real value in the database. – risendy Dec 18 '19 at 14:58
  • Basically im trying to do something like: https://stackoverflow.com/questions/3509350/get-the-last-insert-id-with-doctrine-2 – risendy Dec 18 '19 at 15:07
  • and using this ? `$entityManager->getConnection()->lastInsertId()` – Pierrick Rambaud Dec 18 '19 at 16:00