目前我有以下3表。
article_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 »
任何帮助或提示或任何更好的编写查询的方式都将非常有用。
提前致谢。
最佳答案
您不应在查询构建器中使用表名,而应使用类名。
$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();