【问题标题】:Symfony3 ManyToMany joinSymfony3 多对多加入
【发布时间】:2018-02-22 17:23:30
【问题描述】:

我需要获取类别 ID 为 join ManyToMany 的文章列表,我尝试了一整天,但它不起作用。使用 dql 查询或任何帮助我绝望。 我想获取具有多对多关系的类别 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();

没有用

【问题讨论】:

  • 你尝试了什么?
  • 因为这是我的教育项目,我非常需要它。
  • 请说明您期望得到什么样的结果以及得到的结果。现在有点不清楚。
  • 我想获取获得特定类别的文章列表,例如(类别 id 1)

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


【解决方案1】:

你可以试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多