【发布时间】:2020-09-12 23:13:49
【问题描述】:
我正在使用 Symfony 5 编写博客,但在从 URL 获取 Id 以显示我的数据库中的 cmets 时遇到问题。
总结一下: - 我有一个视图“/fiche/{id}”希望显示特定的游戏信息。 - 人们可以在下面发表评论,评论进入数据库,带有一个名为“jeu_id”的外键希望是发表评论的游戏。
- 目标是现在显示所有希望在此特定游戏上发布的 cmets。我想显示所有带有外键“jeu_id”的 cmets 希望在 url “/fiche/{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(),
]);
}
这是实体“Commentaires”中的关注变量:
/**
* @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;
}
【问题讨论】:
-
抱歉,我不太清楚,您在什么时候遇到了麻烦?你能解释一下究竟是什么不起作用吗?
-
变量“commentaires”什么都不返回,它应该显示所有具有特定外键(url中的id)的cmets
-
您尝试过什么调试问题?获取 ID 非常简单,因为您的控制器已经包含
$id
标签: php sql symfony controller doctrine