Symfony4 setter getter在哪里匹配id路由



我是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
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=255)
*/
private $name;
/**
* @ORMColumn(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()
]);
}

基本上,您必须从请求中获取ID,查询投票实体的Entitty存储库,更新投票并将其保存回数据库。

  1. 从您的请求中获取ID

    $id=$request->query->get('id'(;

  2. 查询存储库:

    $entityManager=$this->getDoctrine((->getManager((;

    $poll=$entityManager->getRepository(poll::class(->find($id(;

  3. 更新投票:

    $poll->setVotes($poll->getVotes((+1(;

  4. 坚持数据库:

    $entityManager->persistent($poll(;

    $entityManager->flush((;

或者,您也可以使用ParamConverter让Symfony为您获取轮询对象。有关更新对象的更多信息,请参阅《条令指南》。

请注意,yor路由将只匹配现有的轮询,因为id是URL中的必需参数。您可以添加另一个没有ID的路由,该路由用于创建新的轮询实体。