如何过滤当前用户拥有的实体

时间:2017-05-12 15:32:06

标签: symfony fosuserbundle dql

我对Symfony很新。

作为用户,我只想看到我创建的实体。 用户可以登录并创建游戏,但我只想看到我创建的游戏实体。 它是用户和游戏的ManyToMany关系,其中User是拥有者。

  

示例:游戏"游戏用户Joop1"只能由用户查看   Joop1。标题为游戏的游戏#34;游戏为Joop2"可能只能被观看   Joop2。

如果将Joop1记录为当前用户,我怎么才能显示他用DQL / querybuilder创建的游戏?

我使用FOSUserBundle。

更新:我已将关系更改为: 用户 - >游戏:多对多。

问题:这个sql语句的dql / querybuilder脚本是什么:

SELECT * FROM game,users_games WHERE users_games.user_id = 1 

这是我目前基于Manuel DUVERNON回答的查询构建器脚本:

$em = $this->getDoctrine()->getManager();

$qb = $em->getRepository( Game::class )->createQueryBuilder( 'game_t' );
$qb->join( 'users_games.user_id', 'ug' )
    ->where( 'ug.user_id = :userId' )
    ->setParameter( 'userId', 1);
return $qb->getQuery()->getResult();

但这不起作用,因为我收到以下错误:

  

[语义错误]第0行,第70行附近' .user_id ug WHERE':错误:   标识变量users_games用于连接路径表达式但是   以前没有定义过。

    GameController

      <?php

    namespace AppBundle\Controller;

    use AppBundle\Entity\Game;
    use AppBundle\Entity\PlayLog;
    use AppBundle\Entity\User;
    use AppBundle\Form\GameType;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\HttpFoundation\Request;
/**
 * Game controller.
 *
 * @Route("game")
 */
class GameController extends Controller
{
    /**
     * Lists all game entities.
     *
     * @Route("/", name="game_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        //get user_id
//
        $usr = $this->getUser();
        $id = $usr->getId();
//
//        $em = $this->getDoctrine()->getManager();
////        $dql="SELECT g FROM AppBundle\Entity\Game g Join g.users u WHERE u.id := user_id";
//        $dql = "SELECT game FROM AppBundle:Game game ";
//        $query = $em->createQuery($dql);
//        $query->setParameter('user_id', $id);
//        $current_games = $query->getResult();


//        $paginator = $this->get('knp_paginator');
//        $result = $paginator->paginate(
//
//            $request->query->getInt('page', 1),
//            $request->query->getInt('limit', 25)
//        );
//        dump(get_class($paginator));



//        $em = $this->getDoctrine()->getManager();
//
//        $current_games = $em->getRepository('AppBundle:Game')->findAll();



//        $em = $this->getDoctrine()->getManager();
//
//        $current_games = $em->getRepository('AppBundle:Game')->findAllOrdered($id);
//
        $em = $this->getDoctrine()->getManager();

        $qb = $em->getRepository( Game::class )->createQueryBuilder( 'game_t' );
        $qb->join( 'users_games.user_id', 'ug' )
            ->where( 'ug.user_id = :userId' )
            ->setParameter( 'userId', $id);
        return $qb->getQuery()->getResult();


        return $this->render('game/index.html.twig', array(
            'games' => $current_games,
            'max_limit_error' => 25
        ));
    }

    /**
     * Creates a new game entity.
     *
     * @Route("/new", name="game_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {

        $game = new Game();

        $form = $this->createForm('AppBundle\Form\GameType', $game);
        $form->handleRequest($request);

        $game->setUser($this->getUser());
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($game);
            $em->flush($game);

            return $this->redirectToRoute('game_show', array('id' => $game->getId()));
        }

        return $this->render('game/new.html.twig', array(
            'game' => $game,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a game entity.
     *
     * @Route("/{id}", name="game_show")
     * @Method("GET")
     */
    public function showAction(Game $game)
    {
        $deleteForm = $this->createDeleteForm($game);


        return $this->render('game/show.html.twig', array(
            'game' => $game,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing game entity.
     *
     * @Route("/{id}/edit", name="game_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Game $game)
    {
        $deleteForm = $this->createDeleteForm($game);
        $editForm = $this->createForm('AppBundle\Form\GameType', $game);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('game_show', array('id' => $game->getId()));
        }

        return $this->render('game/edit.html.twig', array(
            'game' => $game,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),

        ));
    }

    /**
     * Displays a form to edit an existing game entity.
     *
     * @Route("/{id}/log", name="game_log")
     * @Method({"GET", "POST"})
     */
    public function addLogAction(Request $request, Game $game)
    {
        $playlog = new PlayLog();
        $form = $this->createForm(GameType::class, $game);
        $form->handleRequest($request);
        if($form->isSubmitted() && $form->isValid()) {

            //Save playLog
            $em = $this->getDoctrine()->getManager();
            $em->persist($playlog);
            $em->flush();

        }
        // Render / return view incl. formulier.
        return $this->render('game/log.html.twig', array(
            'game' => $game,
            'form' => $form->createView(),
        ));
    }

    /**
     * Deletes a game entity.
     *
     * @Route("/{id}", name="game_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Game $game)
    {
        $form = $this->createDeleteForm($game);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($game);
            $em->flush($game);
        }

        return $this->redirectToRoute('game_index');
    }

    /**
     * Creates a form to delete a game entity.
     *
     * @param Game $game The game entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Game $game)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('game_delete', array('id' => $game->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}

Game Entity

    <?php

    namespace AppBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\Common\Collections\ArrayCollection;
    use Symfony\Component\Validator\Constraints as Assert;

    /**
     * Game
     *
     * @ORM\Table(name="game")
     * @ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository")
     */
    class Game
    {

        /**
         * @ORM\OneToMany(targetEntity="PlayLog", mappedBy="game")
         * @ORM\OrderBy({"date" = "DESC"})
         *
         */
        private $playlogs;




        public function __construct()
        {
            $this->playlogs = new ArrayCollection();
        }

        /**
         * @ORM\ManyToOne(targetEntity="Type", inversedBy="games")
         * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
         */
        private $type;


        /**
         * @ORM\ManyToOne(targetEntity="User", inversedBy="games")
         */
        private $user;
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;


        /**
         * @var string
         * @Assert\NotBlank()
         * @Assert\Length(
         *     min = "3",
         *  max = "100"
         * )
         * @ORM\Column(name="name", type="string", length=255, unique=true)
         */
        private $name;


        /**
         * Get id
         *
         * @return int
         */
        public function getId()
        {
            return $this->id;
        }

        /**
         * @return mixed
         */
        public function getUser()
        {
            return $this->user;
        }

        /**
         * @param mixed $user
         */
        public function setUser($user)
        {
            $this->user = $user;
        }

        /**
         * Set name
         *
         * @param string $name
         *
         * @return Game
         */
        public function setName($name)
        {
            $this->name = $name;

            return $this;
        }

        /**
         * Get name
         *
         * @return string
         */
        public function getName()
        {
            return $this->name;
        }

        /**
         * @return mixed
         */
        public function getType()
        {
            return $this->type;
        }

        /**
         * @param mixed $type
         */
        public function setType($type)
        {
            $this->type = $type;
        }


        /**
         * @return mixed
         */
        public function getPlaylogs()
        {
            return $this->playlogs;
        }

        /**
         * @param mixed $playlogs
         */
        public function setPlaylogs($playlogs)
        {
            $this->playlogs = $playlogs;
        }

        public function addPlayLog(PlayLog $playlog)
        {
            $this->playlog->add($playlog);
            $playlog->setPlayLogs($this);
        }

    }

1 个答案:

答案 0 :(得分:0)

您可以获取当前登录的用户,然后使用 用户ID 请求您的dql查询。
看看:

$usr= $this->getUser();
$id=$usr->getId();
$em=$this->getDoctrine()->getManager();
$dql="SELECT * games FROM Game WHERE Game.user_id := user_id";
$query = $em->createQuery($dql);
$query->setParameter('user_id',$id);
$current_games = $query->getResult();