【问题标题】:Fetch entities by count of his relationships, even if they haven't yet relation (ManyToMany) - Doctrine 2通过他的关系计数来获取实体,即使他们还没有关系(ManyToMany) - Doctrine 2
【发布时间】:2015-05-19 22:24:45
【问题描述】:

我正在尝试通过与另一个实体(名为 Tag)的多对多关系来获取实体集合(名为 Animation)。

这是我的动画实体:

class Animation
{
  /**
   * @ORM\ManyToMany(targetEntity="Company\AppBundle\Entity\Tag",inversedBy="animations")
   */
   protected $tags;

}

还有我的标签实体:

class Tag 
{
  /**
  * @ORM\ManyToMany(targetEntity="Company\AppBundle\Entity\Animation", mappedBy="tags")
  * @ORM\JoinTable(name="animation_tag")
  */
  protected $animations;
}

我只想获取链接少于 3 个标签的动画,即使没有标签已链接到它们。

我使用 Doctrine Query Builder 在我的 AnimationRepository 中创建了一个“findAnimsByTag()”方法,如下所示:

public function findAnimsByTag() {

    return $this->getEntityManager()->createQueryBuilder()
    ->select('a')
    ->from('CompanyAppBundle:Animation', 'a')
    ->join('a.tags', 't')
    ->groupBy('t')
    ->having('COUNT(t) < 3 ')
    ->getQuery()
    ->getResult(); 
}

此查询可以很好地获取不超过 3 个标签的实体,但没有获取尚未关联的实体(如帖子顶部所述)。

我该怎么做?

【问题讨论】:

    标签: php symfony doctrine-orm entity-relationship


    【解决方案1】:

    使用 leftJoin 代替 join

     public function findAnimsByTag() {
    
        return $this->getEntityManager()->createQueryBuilder()
        ->select('a')
        ->from('CompanyAppBundle:Animation', 'a')
        ->leftJoin('a.tags', 't')
        ->groupBy('t')
        ->having('COUNT(t) < 3 ')
        ->getQuery()
        ->getResult(); 
    }
    

    【讨论】:

    • 感谢您的快速回复。但我现在不明白,假设我所有的动画实体还没有关系,新查询只返回第一个实体,而不是我的所有实体(因为没有人有关系,查询应该返回我所有的表,不是?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多