我有两个实体User
和Period
,它们有多多多关联:一个用户属于多个时间段,一个时间段有多个用户。此关联使用UserPeriod
实体。
class Period
{
/**
* @ORMOneToMany(targetEntity="UserPeriod", mappedBy="period")
*/
private $users;
}
class UserPeriod
{
/**
* @ORMId
* @ORMManyToOne(targetEntity="User", inversedBy="periods")
*/
private $user;
/**
* @ORMId
* @ORMManyToOne(targetEntity="Period", inversedBy="users")
*/
private $period;
}
class User extends BaseUser
{
/**
* @ORMOneToMany(targetEntity="UserPeriod", mappedBy="user")
*/
protected $periods;
}
我想要实现的是从一个定义的时期获得所有用户的列表。由于有很多用户,我不能将它们全部加载到内存中,必须对它们进行迭代(批处理)。下面是我的尝试:
public function getUsersOfQuery($period)
{
return $this->_em->createQueryBuilder()
->select('u')
->from('SGLotteryUserBundle:LotteryUser', 'u')
->innerJoin('u.periods', 'p')
->where('p.period = :id')
->setParameter('id', $period->id())
->getQuery();
}
$it = $repo->getUsersOfQuery($period)->iterate();
但是,引发了这个异常:
[DoctrineORMQueryQueryException]
Iterate with fetch join in class UserPeriod using association user not allowed.
我不能使用本机查询,因为User
使用表继承。
Github issue
当使用MANY_TO_MANY或ONE_TO_MANY join in时,会发生这种情况那么你的查询就不能遍历它,因为它是潜在的同一实体可能在多行中。
如果你在你的查询中添加一个distinct,那么一切都会正常工作保证每条记录是唯一的
$qb = $this->createQueryBuilder('o');
$qb->distinct()->join('o.manyRelationship');
$i = $qb->iterator;
echo 'Profit!';