2016-12-30 102 views
1

我有两个实体(Item & Tag)通过双向ManyToMany关系链接,我想显示实际(关键字)中使用的实体(Tag)记录其他实体(项目):如何在ManyToMany Doctrine关系中选择已使用的项目

这里是我的项目实体:

class Item 
{ 
    /** 
    * @ORM\ManyToMany(targetEntity="MyBundle\Entity\Tag", inversedBy="items") 
    */ 
    private $tags; 
} 

我的标签enity:

class Tag 
{ 
    /** 
    * @ORM\ManyToMany(targetEntity="MyBundle\Entity\Item", mappedBy="tags") 
    */ 
    private $items; 
} 

现在在我的标签库我已经试过这样:

class TagRepository extends \Doctrine\ORM\EntityRepository 
{ 
    public function findAllUsed() 
    { 
     return $this->createQueryBuilder('t') 
      ->leftJoin('t.items', 'items') 
      ->groupBy('items.id') 
      ->having('COUNT(t.id) > 0') 
      ->orderBy('t.name', 'ASC') 
      ->getQuery() 
      ->getResult(); 
    } 
} 

但它没有给我我期待的结果......任何人都可以帮忙吗?谢谢!

回答

1

的问题

我没有测试,但它似乎你的错误是计数子句。您正在计数标签having('COUNT(t.id) > 0')。所以它会返回所有标签。 另一个错误是您按'项目'分组并仅选择't'。你不需要分组。

解决方案

更改 '标签' 在having子句 '项目'。

public function findAllUsed() 
{ 
    return $this->createQueryBuilder('t') 
     ->leftJoin('t.items', 'items')    
     ->having('COUNT(items.id) > 0') 
     ->orderBy('t.name', 'ASC') 
     ->getQuery() 
     ->getResult(); 
} 

另一种可能的方式更简单的是做这样一个@KevinTheGreat innerJoin,但检查不会有需要或者where子句中的任何更多:

public function findAllUsed() 
{ 
    return $this->createQueryBuilder('t') 
     ->innerJoin('t.items', 'items')   
     ->orderBy('t.name', 'ASC') 
     ->getQuery() 
     ->getResult(); 
} 
+1

第二种解决方案简单易行!我应该多学习一点SQL语言......感谢Vinicius! – VinZ

1

我这样做,从我的头顶,但它应该工作,我用了一个innerJoin代替leftJoin,然后添加一个地方,以确保您得到的是被链接的记录:

public function findAllUsed() 
    { 
     return $this->createQueryBuilder('t') 
      ->innerjoin('t.items', 'i') 
      ->groupBy('i.id') 
      ->where('i.id = t.items') 
      ->having('COUNT(t.id) > 0') 
      ->orderBy('t.name', 'ASC') 
      ->getQuery() 
      ->getResult(); 
    } 
} 

我用这个例子来制定的答案:Query on a many-to-many relationship using Doctrine with Symfony2

+0

我有错误“‘项目GROUP BY’:错误:PathExpression无效。预期为StateFieldPathExpression或SingleValuedAssociationField。“现在。 – VinZ

+0

您是否已将-groupBy('items.id')更改为('i.id') – KevinTheGreat

+0

您的回答有点多余。因为'where('i.id = t.items')'已经包含在内连接中。 –

相关问题