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,
The FETCH_EAGER mode has it's problems. In fact there is an open request here to resolve this issue but hasn't been closed yet.
I recommend using a custom repository to fetch the data in the manner you want it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With