问题描述:

At present I having following 3 tables.

articles_categories

+-------------+---------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------------+---------+------+-----+---------+-------+

| article_id | int(11) | NO | PRI | NULL | |

| category_id | int(11) | NO | PRI | NULL | |

+-------------+---------+------+-----+---------+-------+

category

+-----------------+--------------+------+-----+---------+----------------+

| Field | Type | Null | Key | Default | Extra |

+-----------------+--------------+------+-----+---------+----------------+

| id | int(11) | NO | PRI | NULL | auto_increment |

| title | varchar(255) | NO | | NULL | |

+-----------------+--------------+------+-----+---------+----------------+

article

+-----------------+--------------+------+-----+---------+----------------+

| Field | Type | Null | Key | Default | Extra |

+-----------------+--------------+------+-----+---------+----------------+

| id | int(11) | NO | PRI | NULL | auto_increment |

| title | varchar(255) | NO | | NULL | |

+-----------------+--------------+------+-----+---------+----------------+

In Category Entity

/**

* @ORM\ManyToMany(targetEntity="Article", mappedBy="categories")

* @ORM\OrderBy({"createdAt" = "DESC"})

*/

protected $articles;

In Article Entity

/**

* All categories this article belongs to.

*

* @ORM\ManyToMany(targetEntity="Category", inversedBy="articles", cascade={"persist"})

* @ORM\JoinTable(name="articles_categories")

*/

protected $categories;

Most of queries works fine. But I want to get articles that belongs to a category. Or that have a specific category or Want to filter Articles based on Category.

For that I wrote following query.

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

But it throws following error.

[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

Any help or hints or any better ways to write queries would be great.

Thanks in Advance.

网友答案:

You should not use table names in your query builder, instead you should use class names.

$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();
相关阅读:
Top