简体   繁体   中英

Symfony3 ManyToMany join

I need to get liste of articles who have the id of categorie with join ManyToMany I tried all day but it won't work. with dql query or anything pelase help I am despread. I want to get liste of articles who have category id with many to many relation

    /**
 *
 * @ORM\ManyToMany(targetEntity="Categorie",mappedBy="cat")
 * @ORM\JoinTable(name="article_categorie",
 *     joinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="categorie_id", referencedColumnName="id",onDelete="CASCADE")}
 *      )
 *
 */
private $categorie;

my first try

$qp=$this->createQueryBuilder('p');
    $qp->select("p")
        ->from(Categorie::class,"c")
        ->where($qp->expr()->eq("c.id","$id"))->setMaxResults(3)
        ->getQuery()->execute();
        return $qp;

my second try

$em = $this->getEntityManager();
    $query = $em->createQuery("SELECT article
            FROM article t
            INNER JOIN article_categorie jt ON(t.id = jt.article_id)
            INNER JOIN categorie g ON(g.id = jt.categorie_id)
            WHERE_id g.id=9");return $query->getResult();

my third try

$this->createQueryBuilder()
        ->select('s')
        ->from('ArticleBundle:Categorie', 's')
        ->innerJoin('s.Category c ON c.category_id = s.')
        ->where('s.name = :superCategoryName')
        ->setParameter('superCategoryName', $superCategoryName)
        ->getQuery()
        ->getResult();

Dosn't work

You can try this:

/**
 * @ORM\Entity
 */
class Article
{
  /**
   * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Category", cascade={"persist"})
   */
  private $categories;

  // …
}

and in your repository:

  public function getArticlesWithCategories(array $categoryNames)
  {
    $qb = $this->createQueryBuilder('a');

    // We're making a joint with the Category entity with alias "c."
    $qb
      ->innerJoin('a.categories', 'c')
      ->addSelect('c')
    ;

     // Then we filter on the names of the categories using an IN
     //If you really need to take the id, replace the $categorieName variable with $categorieID and "c. name" with "c. id".

    $qb->where($qb->expr()->in('c.name', $categoryNames));
    // The syntax of the IN and other expressions can be found in the Doctrine documentation

    // Finally, we return the result
    return $qb
      ->getQuery()
      ->getResult()
    ;
  }

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