我在不同的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(),
);
}
}
答案 0 :(得分:1)
仅显示属于登录用户的帖子:
$user = $this->getUser();
$this->getDoctrine()->getManager()->getRepository('FLYBookingsBundle:Post')->findBy(array('user' => $user ));