允许用户仅对评论投票一次[symfony2]

时间:2016-10-30 15:05:04

标签: php symfony doctrine-orm twig

我有一个表格votecomment我允许用户只对comment_id投票一次。目前,用户可以多次投票以发表评论。

我希望之前能够坚持用户在表格投票中验证当前user_id是否已经投票指定了comment_id,如果是,则投票将不会持续存在。

Controller.php这样

public function voteAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();
    $comment = $em->getRepository('ApplicationSonataUserBundle:Comment')->findOneBy(array('id' => $id));
    $entity = new Vote();
    $entity->setUser($this->get('security.token_storage')->getToken()->getUser());
    $entity->setVotecomment($comment);
    $entity->setCreatedAt(new \DateTime());
    $em->persist($entity);
    $em->flush();
    return $this->redirect($this->generateUrl('userShow', array(
    'entity' => $entity->getVotecomment()->getRecipient(),
    'slug' =>  $entity->getVotecomment()->getRecipient()->getId(),
        )));
}

vote.php

    <?php

    namespace Application\Sonata\UserBundle\Entity;
    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\Common\Collections\Collection;
    use Symfony\Component\Validator\Constraints as Assert;
    use Doctrine\Common\Collections\ArrayCollection;

    /**
     * @ORM\HasLifecycleCallbacks
     * @ORM\Entity
     * @ORM\Entity(repositoryClass="Application\Sonata\UserBundle\Entity\UserRepository")
     * @ORM\Table(name="vote")
     *
     */

    class Vote
    {
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;


        /**
         * @var User
         * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User", inversedBy="likes")
         */
        protected $user;

        /**
         * @var int
         *
         * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\Comment", inversedBy="votes", cascade={"persist"})
         * @ORM\JoinColumn(name="votecomment_id", referencedColumnName="id")
         *
         */
        private $votecomment;

        /**
         * @ORM\Column(name="createdAt", type="datetime", nullable=false)
         */
        protected $createdAt;


        public function __construct()
        {
            $this->setCreatedAt(new \DateTime());

            $this->votecomment = new ArrayCollection();
        }

}

twig文件

<a class="fa fa-thumbs-o-up" href="{{ path('likecomment', {'entity': entity ,'slug': entity.recipient.id ,'id': entity.id}) }}"></a><b class="text-color">&nbsp; &nbsp;{{ entity.votes|length }}</b>

3 个答案:

答案 0 :(得分:1)

我建议使用Symfony Validation component并将UniqueEntity验证约束添加到您的投票实体。使用这种方式,您可以通过两个字段($ user和$ votecomment)验证您的实体唯一性。

答案 1 :(得分:0)

试用此解决方案 当然,您可以通过在评论存储库上创建自定义方法来创建 $ hasVote

public function voteAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $hasVote = $em
        ->getRepository('ApplicationSonataUserBundle:Comment')
        ->find(array(
            'id' => $id,
            'user' => $this->getUser())
        );

    if ($hasVote){

        // Add flash - already voted
        // Redirect to route...
    } else {

        $comment = $em
        ->getRepository('ApplicationSonataUserBundle:Comment')
        ->findOneBy(array('id' => $id));

        $vote = new Vote();
        $vote->setUser($this->getUser());
        $vote->setVotecomment($comment);
        $vote->setCreatedAt(new \DateTime());

        $em->persist($vote);
        $em->flush();

        return $this->redirect($this->generateUrl('userShow', array('entity' => $entity->getVotecomment()->getRecipient(),'slug' =>  $entity->getVotecomment()->getRecipient()->getId(),)));
    }
}

答案 2 :(得分:0)

基本上我只需检查当前用户是否已投票评论。

下面是我如何做到的一个例子:

   public function voteAction(Request $request,$id)
    {
        $em = $this->getDoctrine()->getEntityManager();


        $comment = $em->getRepository('ApplicationSonataUserBundle:Comment')->findOneBy(array('id' => $id));
        $voteExist = $em->getRepository('ApplicationSonataUserBundle:Vote')->findOneBy([
            'user' => $this->getUser(),
            'votecomment' => $comment
        ]);
        $vote = new Vote();
        if(!$voteExist) {

            $vote->setUser($this->get('security.token_storage')->getToken()->getUser());
            $vote->setVotecomment($comment);
            $vote->setCreatedAt(new \DateTime());
            $em->persist($vote);
            $em->flush();

            return $this->redirect($this->generateUrl('userShow', array(
                'entity' => $vote->getVotecomment()->getRecipient(),
                'slug' => $vote->getVotecomment()->getRecipient()->getId(),
            )));



        } else {

            $em->remove($voteExist);
            $em->flush();
            //$this->get('session')->getFlashBag()->add('notice', 'You have already voted!');

        }

        return $this->redirect($this->generateUrl('userShow', array(
            'entity' => $comment->getRecipient(),
            'slug' => $comment->getRecipient()->getId(),
        )));

    }