Symfony / Doctrine:按子属性过滤查询

时间:2017-08-17 07:54:00

标签: php symfony doctrine-orm

我正在尝试执行查询以从特定Repos获取所有Organization,但它返回一个空结果...(我在数据库中有数据!) 回购和组织是Many to Many关系。

这是Repos实体:

/**
 * Repos
 *
 * @ORM\Table(name="repos")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ReposRepository")
 */
 class Repos
 {

     ...

     /**
      * 
      * @ManyToMany(targetEntity="Organization", inversedBy="repos")
      *
      */
     protected $orgs;

     ...

这是Organization实体:

 /**
  * Organization
  *
  * @ORM\Table(name="organization")
  * @ORM\Entity(repositoryClass="AppBundle\Repository
  * \organizationRepository")
  */
  class Organization
  {
      ...

      /**
       *
       * @ORM\ManyToMany(targetEntity="Repos", mappedBy="orgs")
       *
       */
       protected $repos;

      ...
  }

以下是RepositoryQueryBuilder

/**
 * ReposRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
 class ReposRepository extends \Doctrine\ORM\EntityRepository
 {

    public function findReposByName($name){
        $qb = $this->createQueryBuilder('r');

        // Build query
        $qb->select('r')
           ->andWhere(
                ':searchName MEMBER OF r.orgs'
             );
        $qb->setParameter('searchName',$name);
        return $qb->getQuery()->getResult();
    }

 }

$name是组织的名称,我想获得具有相同组织名称的所有Repos。

1 个答案:

答案 0 :(得分:2)

如果您想使用组织的name属性进行过滤,则必须进行加入查询。

使用查询构建器

public function findReposByName($name){
    $qb = $this->createQueryBuilder('r');
    $qb->select('r')
       ->join('r.orgs', 'o')
       ->where('o.name = :searchName')
       ->setParameter('searchName', $name);
    return $qb->getQuery()->getResult();
}

在DQL中

public function findReposByName($name){
    $dql =<<<EOF
        SELECT r
        FROM AppBundle:Repos r
        INNER JOIN r.orgs o
        WHERE o.name = :searchName
EOF;
    return $this->_em
                ->createQuery($dql)
                ->setParameter('searchName',$name)
                ->getResult();
}