title: Symfony - Get last id with doctrine
body: <p>I have just developed a controller that consists of creating a subject with the ability to add one or more questions.
  It works, but I'm not really satisfied with the quality of my code:</p>
  
  <p>Indeed when I want to create a new topic, I can not retrieve the last id of my table QUESTION in phpmyadmin. (I have for the moment two tables: SUBJECT, QUESTION)</p>
  
  <p>The only solution I found, and it is very ugly, is to create the subject, and create a record in my QUESTION table to finally retrieve the last id via getid () by autoincrementation and delete this same question before Display the form for adding a question.</p>
  
  <p>Does any of you have a better solution? :(</p>
  
  <p>Thank you in advance for your return,</p>
  
  <p>My code:</p>
  
  <pre><code>/**
  * @Route("/add_sujet", name="add_sujet")
  * @Method({"GET", "POST"})
  */
  public function add_sujetAction(Request $request)
  {
  
  $sujet = new Sujet();
  
  $form = $this-&gt;createForm(SujetType::class, $sujet)
      -&gt;add('saveAndNext', SubmitType::class);
  $form-&gt;handleRequest($request);
  
  
  if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
      $sujet-&gt;setSlug($this-&gt;get('slugger')-&gt;slugify($sujet-&gt;getTitle()));
      $entityManager = $this-&gt;getDoctrine()-&gt;getManager();
      $entityManager-&gt;persist($sujet);
      $entityManager-&gt;flush();
  
      $this-&gt;addFlash('success', 'sujet.created_successfully');
  
      if ($form-&gt;get('saveAndNext')-&gt;isClicked()) {
          // On commence à créer les questions.
  
          $question = new question();
          $question-&gt;setContent('init');
          $question-&gt;setType('init');
          $question-&gt;setSujet($sujet);
          $entityManager = $this-&gt;getDoctrine()-&gt;getManager();
          $entityManager-&gt;persist($question);
          $entityManager-&gt;flush(); // Add factice question&lt;br&gt;
          $id = $question-&gt;getId()+1; // NOT OPTIMIZED.. &lt;br&gt;
          $entityManager-&gt;remove($question); 
  &lt;br&gt;
          $entityManager-&gt;flush(); // JE SAIS C'EST TRES MOCHE.. &lt;br&gt;
  
          return $this-&gt;redirectToRoute('add_question', ['sujetSlug' =&gt; $sujet-&gt;getSlug(), 'id' =&gt; $id]);
  
      }
      // On annule la création de sujet.
      return $this-&gt;redirectToRoute('sujet');
  }
  // On présente le formulaire pour déclaration sujet.
  return $this-&gt;render('default/add_sujet.html.twig', [
      'sujet' =&gt; $sujet,
      'form' =&gt; $form-&gt;createView(),
  ]);
  
  }
  </code></pre>