0
目前我有以下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;
In Article實體
/**
* 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 »
任何幫助或提示或任何更好的方式來編寫查詢將是偉大的。
在此先感謝。
'articles_categories'不是一個Doctrine映射類,它不是一個ORM類。爲了您的需要,您不需要指定實體之間的關係表,而只需指定它們之間的現有關係。 – Matteo
檢查這個答案的例子http://stackoverflow.com/a/19710312/2270041 – Matteo
@Matteo非常感謝你。你解決了這個問題。 – bharatesh