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?
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");
$qb->expr()->isMemberOf(':user', 'a.authors')
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();
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With