Php Symfony4 setter getter匹配id路线在哪里?

Php Symfony4 setter getter匹配id路线在哪里?,php,symfony,symfony4,Php,Symfony,Symfony4,我对Symfony很熟悉 我在做投票系统,但我想这应该适合 目前我的控制器功能是这样的,它只创建一个具有1vote的新行,而不更新以前创建的任何$id /** * @Route("/public/{id}/vote", name="poll_vote", methods="GET|POST") */ public function vote(Request $request, Poll $poll): Response { $inc = 1;

我对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}) }}">
我不知道如何匹配实体中的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,查询投票实体的EntityRepository,更新投票并将其保留回数据库

  • 从您的请求中获取ID

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

  • 查询存储库:

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

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

  • 更新投票:

    $poll->setvoces($poll->getvoces()+1)

  • 保存到数据库:

    $entityManager->persist($poll)

    $entityManager->flush()

  • 或者,您也可以使用让Symfony为您获取Poll对象。有关更新对象的详细信息,请参阅


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

    $request->query->get('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()
        ]);
        }