可以使用Doctrine的QueryBuilder,通过嵌套关联来解决这个问题。
下面是一个示例,假设有两个实体,Article和Comment,并且每个Article都有多个Comment嵌套在其中:
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
class Article { private $id; private $title; private $comments;
public function __construct()
{
$this->comments = new ArrayCollection();
}
// Getters and setters...
public function addComment(Comment $comment)
{
$this->comments->add($comment);
$comment->setArticle($this);
}
public function removeComment(Comment $comment)
{
$this->comments->removeElement($comment);
$comment->setArticle(null);
}
}
namespace App\Entity;
class Comment { private $id; private $content; private $article;
// Getters and setters...
public function setArticle(Article $article = null)
{
$this->article = $article;
}
public function getArticle(): ?Article
{
return $this->article;
}
}
现在,假设我们要获取所有标题中包含“api”的文章,这些文章中的评论必须包含内容“great”。我们可以使用以下代码:
namespace App\Repository;
use App\Entity\Article; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Common\Collections\Criteria; use Doctrine\ORM\Query\Expr; use Doctrine\Persistence\ManagerRegistry;
class ArticleRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Article::class); }
public function findArticlesWithGreatComments(string $title)
{
$qb = $this->createQueryBuilder('a');
$qb
->join('a.comments', 'c')
->where(
$qb->expr()->andX(
$qb->expr()->like('a.title', ':title'),
$qb->expr()->eq('c.content', ':content')
)
)
->setParameters