Doctrine orm 如何选择同时具有多个项目关系的行
假设我有一个News实体,它有很多标记关系Doctrine orm 如何选择同时具有多个项目关系的行,doctrine-orm,doctrine,query-builder,dql,Doctrine Orm,Doctrine,Query Builder,Dql,假设我有一个News实体,它有很多标记关系 class News { /** * @ORM\ManyToMany(targetEntity="App\Domain\Entity\Vocabulary\Tag") */ private Collection $tags; } 我有这样的疑问: public function getList( array $tags = null, ): Query { if (null !=
class News
{
/**
* @ORM\ManyToMany(targetEntity="App\Domain\Entity\Vocabulary\Tag")
*/
private Collection $tags;
}
我有这样的疑问:
public function getList(
array $tags = null,
): Query {
if (null !== $tags) {
$qb->andWhere('nt.id IN (:tags)');
$qb->setParameter('tags', $tags);
}
}
问题是,当我传递[Tag1,Tag2]时,它选择具有第一个标记或第二个标记的新闻,但不能同时具有这两个标记。如何重写查询以选择同时具有两个标记的新闻?首先要注意的一些事项: 对于条令注释,可以使用::class常量:
use App\Domain\Entity\Vocabulary\Tag;
class News
{
/**
* @ORM\ManyToMany(targetEntity=Tag::class)
*/
private Collection $tags;
}
如果$tags数组为空,则会发生异常,因为空值集是无效的SQL,至少在mysql中是这样:
nt.id IN () # invalid!
现在谈谈问题:
使用SQL聚合函数COUNT和groupby,我们可以计算所有新闻的标记数。连同允许标记的条件,每个新闻的标记数必须等于标记数组中的标记数:
/**
* @var EntityManagerInterface
*/
private $manager;
...
/**
* @param list<Tag> $tags - Optional tag filter // "list" is a vimeo psalm annotation.
*
* @return list<News>
*/
public function getNews(array $tags = []): array
{
$qb = $this->manager
->createQueryBuilder()
->from(News::class, 'news')
->select('news')
;
if(!empty($tags)) {
$tagIds = array_unique(
array_map(static function(Tag $tag): int {
return $tag->getId();
}) // For performance reasons, give doctrine ids instead of objects.
); // Make sure duplicate tags are handled.
$qb
->join('news.tags', 'tag')
->where('tag IN (:tags)')
->setParameter('tags', $tagIds)
->addSelect('COUNT(tag) AS HIDDEN numberOfTags')
->groupBy('news')
->having('numberOfTags = :numberOfTags)
->setParameter('numberOfTags', count($tags))
;
}
return $qb
->getQuery()
->getResult()
;
}