Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine - how to check if a collection contains an entity

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?

like image 459
mleko Avatar asked Mar 28 '17 15:03

mleko


2 Answers

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");
like image 71
mleko Avatar answered Oct 18 '22 06:10

mleko


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->setParameter('user', $author);

    $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>
    
like image 33
Erdal G. Avatar answered Oct 18 '22 06:10

Erdal G.