仅显示登录用户创建的内容.Symfony2.8

时间:2016-01-10 17:20:42

标签: php symfony entity relationship fosuserbundle

我在不同的bundle中有两个表Post实体是链接到表User的实体。问题是每个登录的用户都可以看到所有产品,只想允许(显示)登录用户创建的内容。

在我的PostRepository.php中,我添加了这段代码,但它不起作用:

<?php

namespace FLY\BookingsBundle\Entity;

use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository
{
    public function createAction()
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select('i')
            ->from('FLYBookingsBundle:Post', 'i')
            ->where('i.roles LIKE :roles')
            ->setParameter('roles', '%owner object%');

        return $qb->getQuery()->getResult();
    }
}

post.php中

<?php

namespace FLY\BookingsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Application\Sonata\UserBundle\Entity\User;

/**
 * Post
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="FLY\BookingsBundle\Entity\PostRepository")
 */
class Post
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     *
     *
     * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
     * @ORM\JoinColumn(onDelete="CASCADE")
     */
    private $owner;



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


/**
     * @return User
     */
    public function getOwner()
    {
        return $this->owner;
    }

    /*
     * @param User $owner
     */
    public function setOwner(User $owner)
    {
        $this->owner = $owner;

        return $this;
    }
}

PostController.php

    public function createAction(Request $request)
    {
        $entity = new Post();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $user = $this->getUser();
            $entity->setOwner($user);
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('post_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }
}

1 个答案:

答案 0 :(得分:1)

仅显示属于登录用户的帖子:

  1. 每个帖子都必须与用户相关联。在Post实体和User实体之间创建ManyToOne关系。请参阅此documentation,因为您的代码太稀疏,无法猜测如何最好地提供解决方案。
  2. 您的展示操作需要限制为已登录的用户。请参阅此documentation
  3. 限制展示操作后,请让用户参与其中:$user = $this->getUser();
  4. 使用$ user,$this->getDoctrine()->getManager()->getRepository('FLYBookingsBundle:Post')->findBy(array('user' => $user ));