简体   繁体   English

Symfony3 ManyToMany加入

[英]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. 我需要获取一整天都在尝试加入joinToToy的具有类别ID的文章列表,但我无法使用。 with dql query or anything pelase help I am despread. 与dql查询或其他任何可帮助我理解的内容。 I want to get liste of articles who have category id with many to many relation 我想获取具有多对多关系类别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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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