我的 product
实体中有这个映射属性:
/**
* @ORM\ManyToMany(targetEntity="Group", mappedBy="products", indexBy="id", fetch="EAGER")
*
*/
protected $groups;
我想知道,我对 fetch="EAGER"
的理解是,一旦选择了产品,它就应该获取组,这就是发生的情况,但每当我执行类似 的操作时,它都会使用 2 个查询>findBy()
一个查询获取 product
,另一个获取 groups
。
有没有办法让 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- 覆盖 findBy 是一种好方法吗?有什么缺点吗?
谢谢,
最佳答案
FETCH_EAGER 模式有它的问题。事实上有一个开放的请求here解决此问题但尚未关闭。
我建议使用自定义存储库以您想要的方式获取数据。
关于php - Symfony2 : does fetch ="EAGER" create a join?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19421861/