doctrine-orm - 如何选择在多对多关系中同时具有这两个项目的行
问题描述
假设我有“新闻”实体,它具有多对多“标签”关系
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
-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 聚合函数COUNT
,GROUP 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()
;
}
推荐阅读
- java - 如何访问以编程方式添加到自定义视图的视图?
- reactjs - 为什么获取 scrollIntoView 不是函数
- reactjs - 通用挂钩的更新值
- here-api - 使用 HERE 进行路线优化和交付窗口
- c++ - 构建良好,但在 Eclipse CDT C++ 项目中突出显示错误
- python - 为什么我会随机获得超高的困惑?
- c++ - 试图故意引发内存泄漏和堆栈溢出,但没有看到内存增长或程序减慢计算机速度
- swift - 从 TrueDepth 传感器改进保存的深度数据图像
- c++ - WSA UDP 套接字无法重用,因为它强制关闭连接
- asp.net - 在 ASP.NET 项目 VB 中创建命名空间