我有两个实体,文章实体和标签实体。这两个实体之间存在 ManyToMany 关系(一篇文章可以有 0->N 个标签,一个标签可以包含在 0->N 篇文章中)
我想要在某些条件下搜索文章(我必须使用查询生成器,像 findBy() 这样的魔术方法还不够),这些条件之一是选择恰好包含 N 个特定标签的文章
我尝试了几次以获得预期的结果但没有成功。我想我误解了学说如何与连接表一起工作。我最后一次尝试:
public function search($titles, $tags, $authors)
{
$query = $this->createQueryBuilder('a') // a = article
->orderBy('a.createdAt', 'DESC')
->setMaxResults($limit)
->setFirstResult($offset);
if($titles !== null){
// ...
}
// tags is an array of string containing names of searched tags (ex : $tags = ['english', 'french', 'game', 'guide'] )
if($tags !== null){
// $query->innerJoin('a.tags', 't');
// $tagsQuery = "";
// foreach ($tags as $id => $tag){
// if($id > 0) $tagsQuery .= " AND ";
// $tagsQuery .= "t.name LIKE :tag_".$id;
// $query->setParameter("tag_".$id, '%'.$tag.'%');
// }
// $query
// ->andWhere($tagsQuery);
$query->leftjoin ('a.tags','t');
foreach ($tags as $id => $tag){
// $query->andWhere("t.name LIKE :tag_".$id);
// $query->setParameter("tag_".$id, '%'.$tag.'%');
$query
->addSelect('t')
->andwhere("t.name LIKE :tag_".$id)
->setParameter("tag_".$id, '%'.$tag.'%');
}
}
// ...
预期结果的示例:
有 3 篇文章:
- id 1
- tags :
- guide
- game
- id 2
- tags :
- english
- id 3
- tags :
- english
- guide
该方法search(null, ['guide','english'], null)必须只返回 id 为 3 的文章
蝴蝶刀刀
慕雪6442864