首页 > 解决方案 > 如何选择在多对多关系中同时具有这两个项目的行

问题描述

假设我有“新闻”实体,它具有多对多“标签”关系

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"] 时,它会选择具有第一个标签或第二个标签的新闻,但不能同时具有这两个标签。如何重写查询以选择同时具有两个标签的新闻?

标签: doctrine-ormdoctrinequery-builderdql

解决方案


首先要注意的一些事项:

对于教义注释,可以使用::class-constant:

use App\Domain\Entity\Vocabulary\Tag;

class News
{
    /**
     * @ORM\ManyToMany(targetEntity=Tag::class)
     */
    private Collection $tags;
 }

如果$tags数组为空原则会抛出异常,因为空值集是无效的 SQL,至少在 mysql 中:

nt.id IN () # invalid!

现在解决问题:

使用 SQL 聚合函数COUNTGROUP BY我们可以计算所有新闻的标签数量。连同您对允许标签的条件,每个新闻的标签数必须等于标签数组中的标签数:

/**
 * @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()
    ;
}

推荐阅读