如何在url中获得id来显示symfony5的注解?

xzabzqsa  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(283)

我正在用symfony5编写一个博客,我在从url获取id以显示数据库中的评论时遇到了问题。
总而言之:-我有一个视图“/fiche/{id}”wish显示特定的游戏信息。-人们可以在下面留言,留言进入数据库,外键名为“jeuïid”wish是留言发布的游戏。
我们的目标是现在显示所有的评论希望张贴在这个特定的游戏。我想在url“/fiche/{id}”中显示外键为“jeu\u id”的所有评论。
以下是我的控制器中的方法:

/**
     * @Route("/fiche/{id}", name="fiche", methods={"POST", "GET"})
     */
    public function fiche($id, Jeux $jeux, Request $request): Response
    {
        $id = (int)$request->get('id');
        $commentaires = $this->getDoctrine()->getRepository(Jeux::class)->find($id);

        $commentaire = new Commentaires();
        $commentaire->setCreatedAt(new \DateTime("NOW"));
        $request = Request::createFromGlobals();
        $commentaire->setJeu($jeux);
        $form = $this->createForm(CommentairesType::class, $commentaire);
        $form->handleRequest($request);

        //test variable
        //dd($id);
        dd($commentaire->getJeu($id));

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($commentaire);
            $entityManager->flush();

            return $this->redirectToRoute('liste');
        }
        return $this->render('main/fiche.html.twig', [
            'commentaires' => $commentaires,
            'jeux' => $jeux,
            'form' => $form->createView(),
        ]);
    }

以下是实体“评论”中的关注变量:

/**
     * @ORM\ManyToOne(targetEntity=Jeux::class, inversedBy="commentaires")
     * @JoinColumn(name="jeu_id", referencedColumnName="id")
     * @ORM\JoinColumn(nullable=true)
     */
    private $jeu;

    public function getJeu(): ?Jeux
    {
        return $this->jeu;
    }

    public function setJeu($jeu): self
    {
        $this->jeu = $jeu;

        return $this;
    }

以下是实体“jeux”中的关注变量:

/**
     * @ORM\OneToMany(targetEntity=Commentaires::class, mappedBy="jeu", orphanRemoval=true)
     */
    private $commentaires;

    /**
     * @return Collection|Commentaires[]
     */
    public function getCommentaires(): Collection
    {
        return $this->commentaires;
    }
lb3vh1jj

lb3vh1jj1#

我认为正确的方法是这样的:

/**
 * @Route("/fiche/{jeux}", 
 * name="fiche"
 */
public function fiche(Request $request, Jeux $jeux, EntityManagerInterface $em): Response
{
    $form = $this->createForm(CommentaireType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $commentaire = $form->getData();
        $commentaire->setCreatedAt(new \DateTime("NOW"));
        $jeux->addCommentaire($commentaire);

        $em->persist($commentaire);
        $em->flush();

        return $this->redirectToRoute('liste');
    }

    return $this->render('main/fiche.html.twig', [
        'commentaires' => $jeux->getCommentaires(),
        'jeux' => $jeux,
        'form' => $form->createView(),
    ]);
}

相关问题