简体   繁体   中英

Doctrine query with ManyToMany relation

I have a simple relation ManyToMany between two entities "article" and "category" (for a blog). I would like to fetch every article with a particular category, but I don't know how to create that query. What I did is :

$query = $em->createQuery(
        'SELECT u
        FROM SiteBlogBundle:article u
        WHERE u.categorie.name = :cat
        ORDER BY u.date DESC'
    )
        ->setParameter('cat', '$cateogory')

The line WHERE u.categorie.name = :cat doesn't work. How can I achieve that?

If you are okay with using a query-builder for better readability instead of DQL:

$articles = $em
    ->getRepository('SiteBlogBundle:Article')
    ->createQueryBuilder('article')
        ->leftJoin('article.category', 'category')
        ->where('category.name = :category_name')
        ->orderBy('article.date', 'DESC')
        ->setParameter('category_name', $category->getName())
        ->getQuery()
        ->getResult()
;

But i would strongly advise you to put this query into the repository like this:

// ArticleRepository.php

public function findArticlesByCategoryName($name)
{
    return $this->createQueryBuilder('article')
        ->leftJoin('article.category', 'category')
        ->where('category.name = :category_name')
        ->orderBy('article.date', 'DESC')
        ->setParameter('category_name', $name)
        ->getQuery()
        ->getResult()
    ;
}

Then inside your controller just do:

public function getArticles(Category $category)
{
   $em = $this->getDoctrine()->getEntityManager();
   return $em->
       getRepository('SiteBlogBundle:Article')
       ->findArticlesByCategoryName($category->getName())
   ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM