我正在使用 Doctrine 查询生成器,并且有一个非常具体的要求。
我在实体中使用与用户实体关联(用户帐户实体数组)相关的 ManyToMany 字段。
/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="User", cascade={"persist"})
* @ORM\JoinTable(name="post_user_list")
*/
protected $userList;
显示“公开帖子”的要求包括实体的已发布 bool 值设置为 true、发布日期小于当前日期以及与实体关联的两个用户。
在我的查询生成器中,我进行了这样的设置:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select($select)->from($this->getEntityName(), 'p');
$criteria = $qb->expr()->andX();
$criteria->add($qb->expr()->eq('p.editor_published', 1))
->add($qb->expr()->lte('p.datePublished', ':now'));
并且仅处理前两个要求,现在我需要一个条件条目来计算 userList 中的用户实体数量,以及专门用于大于或等于两个用户的 where 子句。
不完全确定该从哪里继续..
最佳答案
试试这个。该查询使用 HAVING
仅显示与 2 个或更多用户关联的实体。
$qb->select($select)
->from($this->getEntityName(), 'p')
->innerJoin('p.userList','u')
->where('p.editor_published = 1')
->andWhere('p.datePublished <= :now')
->groupBy($select) //not sure what's in $select may need to change this
->having('count(u.id) > 1'); //assuming user has an id column otherwise change it
->setParameter('now',new \DateTime());
关于symfony - Doctrine 查询生成器,其中 ManyToMany 的计数大于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23506960/