Symfony3 ManyToMany加入

时间:2018-02-22 17:23:30

标签: php symfony doctrine-orm orm many-to-many

我需要了解具有类别id的文章并加入ManyToMany我整天都在尝试但是它不起作用。用dql查询或任何pelase帮我解读。 我想听听有多个关系的类别ID的文章

    /**
 *
 * @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;

我的第一次尝试

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

我的第二次尝试

$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();

我的第三次尝试

$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();

无法工作

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

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

  // …
}

并在您的存储库中:

  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()
    ;
  }