Symfony - 用doctrine获取最后一个id

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:

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)

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.

Does any of you have a better solution? :(

Thank you in advance for your return,

My code:

/**
* @Route("/add_sujet", name="add_sujet")
* @Method({"GET", "POST"})
*/
public function add_sujetAction(Request $request)
{

$sujet = new Sujet();

$form = $this->createForm(SujetType::class, $sujet)
    ->add('saveAndNext', SubmitType::class);
$form->handleRequest($request);


if ($form->isSubmitted() && $form->isValid()) {
    $sujet->setSlug($this->get('slugger')->slugify($sujet->getTitle()));
    $entityManager = $this->getDoctrine()->getManager();
    $entityManager->persist($sujet);
    $entityManager->flush();

    $this->addFlash('success', 'sujet.created_successfully');

    if ($form->get('saveAndNext')->isClicked()) {
        // On commence à créer les questions.

        $question = new question();
        $question->setContent('init');
        $question->setType('init');
        $question->setSujet($sujet);
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($question);
        $entityManager->flush(); // Add factice question<br>
        $id = $question->getId()+1; // NOT OPTIMIZED.. <br>
        $entityManager->remove($question); 
<br>
        $entityManager->flush(); // JE SAIS C'EST TRES MOCHE.. <br>

        return $this->redirectToRoute('add_question', ['sujetSlug' => $sujet->getSlug(), 'id' => $id]);

    }
    // On annule la création de sujet.
    return $this->redirectToRoute('sujet');
}
// On présente le formulaire pour déclaration sujet.
return $this->render('default/add_sujet.html.twig', [
    'sujet' => $sujet,
    'form' => $form->createView(),
]);

}

Just select from your table and ORDER BY the id DESC, and LIMIT to 1 record. Creating a new record just to get the last insert id is crazy!

You don't need to add a new record to get the last id. You may try this:

$lastQuestion = $em->getRepository('AppBundle:Question')->findOneBy([], ['id' => 'desc']);
$lastId = $lastQuestion->getId();

To get the last id after flush:

$em->persist($question); // Id not avalaible
$em->flush();
$lastId = $question->getId(); // we can now get the Id