Symfony2: does fetch=“EAGER” create a join?

寵の児 提交于 2020-01-03 13:20:26

问题


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,


回答1:


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.



来源:https://stackoverflow.com/questions/19421861/symfony2-does-fetch-eager-create-a-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!