5

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

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

我想知道,我的理解fetch="EAGER"是,一旦选择了产品,它就应该获取组,这就是发生的情况,但是每当我执行findBy()一个查询来获取 .product和另一个查询来获取groups.

无论如何要制作findBy()或其他帮助方法在一个查询中得到productgroups,或者唯一的方法是编写自定义存储库函数并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-覆盖 findBy 是一个好方法吗?有什么缺点吗?

谢谢,

4

1 回答 1

1

FETCH_EAGER 模式有它的问题。事实上,这里有一个开放的请求解决这个问题,但还没有关闭。

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

于 2013-10-22T06:00:48.877 回答