Doctrine2通过QueryBuilder获取具有许多ToMany关联的行


Doctrine2 fetching rows that have manyToMany association by QueryBuilder

每个人。我有两个实体城市和POI。映射如下:

class City {
/**
 * @ORM'ManyToMany(targetEntity="POI", mappedBy="cities")
 * @ORM'OrderBy({"position" = "ASC"})
 */
protected $pois;

class POI {
/**
 * @ORM'ManyToMany(targetEntity="City", inversedBy="pois")
 * @ORM'JoinTable(name="poi_cities")
 */
protected $cities;

我想使用QueryBuilder获取与某个城市至少有1个关联的所有POI。我可能应该使用exists((函数,但我不知道该怎么做。

您必须Left join它们并检查cities是否为null。

$qb->select('p', 'c')
   ->from('AcmeDemoBundle:POI', 'p')
   ->leftJoin('p.cities', 'c')
   ->where('c IS NOT NULL');

我还没有测试过,但我希望它能给你一个大致的方向。您可以从这里阅读更多关于QueryBuilder的信息。

Docrine2在2013年发生了更改,因此其他解决方案显示错误Error: Cannot add having condition on a non result variable.现在我们不能将联接的别名仅用作条件变量。我们应该使用它的任何属性,如c.id

所以你应该把代码固定到

$qb->select('p', 'c')
   ->from('AcmeDemoBundle:POI', 'p')
   ->leftJoin('p.cities', 'c')
   ->where('c.id IS NOT NULL');
$results = $qb->getQuery()->execute();

如果要选择没有任何城市的实体,请使用IS NULL

$qb->leftJoin('p.cities', 'city')
    ->where('city.id IS NULL')
    ->getQuery()
    ->execute();

对问题的描述以及负责该问题的提交的链接——http://www.doctrine-project.org/jira/browse/DDC-2780