I have this mapped property inside my product entity:
/**
* @ORM\ManyToMany(targetEntity="Group", mappedBy="products", indexBy="id", fetch="EAGER")
*
*/
protected $groups;
I wonder, my understanding for fetch="EAGER" is that it should get the groups once the product is selected, this is what happens but it uses 2 queries whenever i do something like findBy() one query to get the product and another one to get the groups.
Is there anyway to make findBy() or other helper methods get the product along with its groups in one query or the only way is to write a custom repository function and do a LEFT-JOIN myself?
UPDATE
I tried multiple solutions and endup overwriting the findBy() function something like:
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
$q = $this
->createQueryBuilder('u')
->select('u, g')
->leftJoin('u.groups', 'g')
->setFirstResult( $offset )
->setMaxResults( $limit );
foreach ($criteria as $field => $value)
{
$q
->andWhere(sprintf('u.%s = :%s', $field, $field))
->setParameter($field, $value)
;
}
foreach ($orderBy as $field => $value)
{
$q->addOrderBy(sprintf('u.%s',$field),$value);
}
try
{
$q = $q->getQuery();
$users = $q->getResult();
return $users;
}
catch(ORMException $e)
{
return null;
}
}
Questions
1- Can i use fetch="EAGER" to make findBy return the product along with its groups in one query
2- If not then is there any case that i use fetch="EAGER" with many-to-many entities without killing performance
3- Is overriding the findBy is a good approach? any drawbacks?
Thanks,
EAGERfetching. Now that I think of it, I'm not really sure. I will try this as soon as I get to my dev box...