Doctrine - 如何检查集合是否包含实体

时间:2017-03-28 15:40:46

标签: doctrine-orm dql

我有两个实体UserArticle具有多对多关系,因为Article可以有很多作者。

class User
{
    /** @var string */
    public $name;

    /** @var Collection<Article> */
    public $articles;
}

class Article
{
    /** @var string */
    public $title;

    /** @var Collection<User> */
    public $authors;
}

如何使用DQL查找指定(共)作者的所有文章?

2 个答案:

答案 0 :(得分:10)

使用MEMBER OF表达式。

您的DQL查询可能与

类似
SELECT art FROM Article art WHERE :user MEMBER OF art.authors

或使用查询构建器

$queryBuilder = $repository->createQueryBuilder("art");
$queryBuilder->where(":user MEMBER OF art.authors");

或者,您可以加入并过滤收藏

SELECT art FROM Article art JOIN art.authors aut WHERE aut = :user

$queryBuilder = $repository->createQueryBuilder("art");
$queryBuilder->join("art.authors", "aut");
$queryBuilder->where("aut = :user");

答案 1 :(得分:1)

使用查询生成器

摘要

The static method in Animal
The static method in Cat
The instance method in Cat
The instance method in Cat

解决方案

src / Repository / ArticleRepository.php

$qb->expr()->isMemberOf(':user', 'a.authors')

示例用法

src / Controller / ArticleController.php

/**
 * @param User $author
 * @return Article[] List of articles filtered by $author
 */
public function findByAuthor(User $author): array
{
    $qb = $this->createQueryBuilder('a');

    $qb->where($qb->expr()->isMemberOf(':user', 'a.authors'));

    return $qb->getQuery()->getResult();
}

templates / articles.html.twig

/**
 * @Route("/article/{id<\d+>}", name="show-articles-by-author")
 * @param ArticleRepository $articleRepository
 * @param User $author
 */
public function showArticlesFromAuthor(ArticleRepository $articleRepository, User $author)
{
    $articles = $articleRepository->findByAuthor($author);

    return $this->render('articles.html.twig', [
        'articles' => $articles, 
        'author'   => $author->getName()
    ]);
}