【发布时间】:2018-11-11 08:47:27
【问题描述】:
我是 Symfony 的新手
我正在做一个投票系统,但我想这应该适用,
目前我的控制器功能是这样的,这只会创建一个带有 1vote 的新行,但不会更新之前创建的任何 $id。
/**
* @Route("/public/{id}/vote", name="poll_vote", methods="GET|POST")
*/
public function vote(Request $request, Poll $poll): Response
{
$inc = 1;
$em = $this->getDoctrine()->getManager();
$entity = new Poll();
$entity->setVotes($inc++);
$em->persist($entity);
$em->flush();
}
return $this->redirectToRoute('poll_public');
}
这是我的树枝模板中的按钮
<a href="{{ path('poll_vote', {'id': poll.id}) }}">
这是我的实体
class Poll
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $votes;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getVotes(): ?int
{
return $this->votes;
}
public function setVotes(?int $votes): self
{
$this->votes = $votes;
return $this;
}
}
我不知道如何从我的实体中匹配我的 getID 并从@Route 中匹配 $id。
任何指导或建议将不胜感激。
谢谢
编辑:
在 Arne 回答后更新了正确的函数:
/**
* @Route("/public/{id}", name="poll_vote", methods="GET|POST")
*/
public function vote($id)
{
$entityManager = $this->getDoctrine()->getManager();
$poll = $entityManager->getRepository(Poll::class)->find($id);
if (!$poll) {
throw $this->createNotFoundException(
'No polls found for id '.$id
);
}
$poll->setVotes($poll->getVotes()+1);
$entityManager->flush();
return $this->redirectToRoute('poll_public', [
'id' => $poll->getId()
]);
}
【问题讨论】:
-
$request->query->get('id')