Symfony2过滤器控制器中的相关实体

时间:2014-06-23 11:08:12

标签: php symfony orm doctrine-orm

我有一个实体"注意",它链接到我的实体"用户"在ManyToMany关系中。从我的用户实体,我想获得符合特定条件的所有Notes。

我知道通过ORM你可以做到这一点:

$this->getDoctrine()->getRepository('PmbLicensingBundle:Note')->findBy(array('criteria' => $value));

通过在实体上调用方法可以做同样的事情,例如:

$this->getUser()->getSharedNotes(array('criteria' => $value));

或者,有没有办法使用以前的ORM命令在ManyToMany关系中进行过滤,例如:

$this->getDoctrine()->getRepository('PmbLicensingBundle:Note')->findBy(array('criteria' => $value, sharedUsers CONTAINS $this->getUser()));

摘自Entity User.php:

/**
 * User
 *
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @Ser\ExclusionPolicy("all")
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Ser\Expose
     */
    protected $id;

    /**
      * @var User[]
      * 
      * @ORM\ManyToMany(targetEntity="Pmb\LicensingBundle\Entity\User", inversedBy="sharedNotes")
      * @Ser\Expose
     **/
    protected $sharedUsers;

    ...
}

摘自Entity User.php

/**
 * User
 *
 * @ORM\Entity
 * @ORM\Table(name="users")
 * @Ser\ExclusionPolicy("all")
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Ser\Expose
     */
    protected $id;


    /**
      * @var Note[]
      * 
      * @ORM\ManyToMany(targetEntity="Pmb\LicensingBundle\Entity\Note", mappedBy="sharedUsers")
      * @Ser\Expose
     **/
    protected $sharedNotes;

    ...
}

或者,对ManyToMany或OneToMany属性的推荐解决方案匹配条件是什么?我更愿意在不依赖实体管理器的情况下执行此操作。

2 个答案:

答案 0 :(得分:1)

您可以为此创建自定义查询。例如,要与用户Notes共享所有$user,请写:

    $em = $this->getDoctrine()->getManager();
    $notes = $em->getRepository('PmbLicensingBundle:Note')
        ->createQueryBuilder('Note')
        ->leftJoin('Note.sharedUsers', 'SharedUsers')
        ->where('SharedUsers = :user')
        ->setParameter('user', $user)
        ->getQuery()
        ->getResult()
        ;

那应该像这样执行查询:

SELECT n0_.id AS id0 
FROM notes n0_ 
LEFT JOIN note_user n2_ ON n0_.id = n2_.note_id 
LEFT JOIN users u1_ ON u1_.id = n2_.user_id 
WHERE u1_.id = {userId}

答案 1 :(得分:1)

使用Criteria类可以过滤收集。

$group          = $entityManager->find('Group', $groupId);
$userCollection = $group->getUsers();

$criteria = Criteria::create()
    ->where(Criteria::expr()->eq("birthday", "1982-02-17"))
    ->orderBy(array("username" => Criteria::ASC))
    ->setFirstResult(0)
    ->setMaxResults(20)
;

$birthdayUsers = $userCollection->matching($criteria)

有关详细信息,请参阅http://doctrine-orm.readthedocs.org/en/latest/reference/working-with-associations.html#filtering-collections