Doctrine - how to check if a collection contains an entity

自作多情 提交于 2020-12-05 10:02:11

问题


I have two entities User and Article with many-to-many relation as Article can have many authors.

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

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

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

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

How I can find all Articles with specified (co)author using DQL?


回答1:


Use MEMBER OF expression.

Your DQL query could like like

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

or using query builder

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

Alternatively you can join and filter collection

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

or

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



回答2:


Use Query Builder

Summary

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

Solution

src/Repository/ArticleRepository.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();
}

Example use

src/Controller/ArticleController.php

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

templates/articles.html.twig

<h1>Articles from {{ author }}</h1>

<li>
    {% for article in articles %}
        <ul>
            {{ article.title }}
        </ul>
    {% endfor %}
</li>
    


来源:https://stackoverflow.com/questions/43073982/doctrine-how-to-check-if-a-collection-contains-an-entity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!