目前我有3张桌子。
articles_categories
+-------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| article_id | int(11) | NO | PRI | NULL | |
| category_id | int(11) | NO | PRI | NULL | |
+-------------+---------+------+-----+---------+-------+
类别
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(255) | NO | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
制品
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(255) | NO | | NULL | |
+-----------------+--------------+------+-----+---------+----------------+
在类别实体
中/**
* @ORM\ManyToMany(targetEntity="Article", mappedBy="categories")
* @ORM\OrderBy({"createdAt" = "DESC"})
*/
protected $articles;
在文章实体中
/**
* All categories this article belongs to.
*
* @ORM\ManyToMany(targetEntity="Category", inversedBy="articles", cascade={"persist"})
* @ORM\JoinTable(name="articles_categories")
*/
protected $categories;
大多数查询都运行正常。但我想获得属于某一类别的文章。或者具有特定类别或想要根据类别过滤文章。
为此,我写了以下查询。
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder('c');
$qb->select('1')
->from('articles_categories', 'a_c')
->leftJoin('\\Chip\\Entity\\Article', 'a', 'WITH', 'a.id = a_c.article_id')
->leftJoin('\\Chip\\Entity\\Category', 'c', 'WITH', 'c.id = a_c.category_id')
;
$result = $qb->getQuery()->getResult();
但它会引发跟随错误。
[Semantical Error] line 0, col 14 near 'articles_categories': Error: Class 'articles_categories' is not defined.
500 Internal Server Error - QueryException
1 linked Exception: QueryException »
任何帮助或提示或任何更好的查询方式都会很棒。
先谢谢。
答案 0 :(得分:1)
您不应在查询构建器中使用表名,而应使用类名。
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder('c');
$qb->select('c', 'a')
->from('Chip\Entity\Category', 'c') // this line is not necessary when performing this query in your category repository
->leftJoin('c.articles, a')
->where('c.id = 1');
$result = $qb->getQuery()->getResult();