Symfony2:fetch=“EAGER”是否创建一个连接


Symfony2: does fetch="EAGER" create a join?

我的product实体中有这个映射属性:

/**
 * @ORM'ManyToMany(targetEntity="Group", mappedBy="products", indexBy="id", fetch="EAGER")
 *
 */
protected $groups;

我想知道,我对fetch="EAGER"的理解是,一旦选择了产品,它就应该获取组,这就是发生的事情,但是每当我执行诸如findBy()一个查询以获取product和另一个查询以获取groups之类的事情时,它都会使用2个查询。

有没有办法让findBy()或其他帮助程序方法在一个查询中获取product及其groups,或者唯一的方法是编写自定义存储库函数并自己做一个LEFT-JOIN

更新

我尝试了多种解决方案,最终覆盖了findBy()函数,如下所示:

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

问题

1-我可以使用fetch="EAGER"使findby在一个查询中返回product及其groups

2-如果没有,那么我是否对多对多实体使用fetch="EAGER"而不会杀死性能

3-覆盖查找方法是好方法吗? 有什么缺点吗?

谢谢

FETCH_EAGER模式有它的问题。实际上,这里有一个未解决该问题的开放请求,但尚未关闭。

我建议使用自定义存储库以您想要的方式获取数据。