HessianMad HessianMad - 1 month ago 8
PHP Question

Empty data when executing a query in Doctrine/Symfony

I'm trying to execute a query to obtain all the

Repos
from an specific
Organization
, but it returns an empty result... (I have data in the DB!)
Repos and Organization are a
Many to Many
relation.

Here's the
Repos
Entity:

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

...

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

...


Here's the
Organization
Entity:

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

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

...
}


Here's the
Repository
with the
QueryBuilder
:

/**
* 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();
}

}


The
$name
is the name of an Organization and I want to obtain all the Repos with the the same organization name.

Answer Source

If you want to filter with the name attribute of your Organization, you have to do a join query.

With the query builder

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();
}

In 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();
}