我有两个实体User
和Article
具有多对多关系,因为Article
可以有很多作者。
class User
{
/** @var string */
public $name;
/** @var Collection<Article> */
public $articles;
}
class Article
{
/** @var string */
public $title;
/** @var Collection<User> */
public $authors;
}
如何使用DQL查找指定(共)作者的所有文章?
答案 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()
]);
}