【问题标题】:Symfony4 setter where getter match id route?Symfony4 setter在哪里getter匹配id路由?
【发布时间】: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-&gt;query-&gt;get('id')

标签: php symfony symfony4


【解决方案1】:

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

  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->persist($poll);

    $entityManager->flush();

您也可以使用ParamConverter 让 Symfony 为您获取 Poll 对象。有关更新对象的更多信息,请参阅Doctrine Guide

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

【讨论】:

  • 感谢 Arne,这正是我想要的,现在正在按我的预期工作。谢谢!。
猜你喜欢
  • 2017-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多