我遇到此查询的问题。我想只获得带有属性$ categoria的汽车,我这样做:
public function listcategoriaAction($categoria)
{
$posts = $this->get('doctrine')->getManager()->createQueryBuilder()->select('p')->from('CarsCarsBundle:Post', 'p')->where('p.categoria = :categoria')->setParameter('categoria', $categoria)->getQuery()->getResult();
return $this->render('CarsCarsBundle:Cars:list.html.twig', array('posts' => $posts));
}
但我收到的是一个空数组。任何提示将不胜感激
答案 0 :(得分:-1)
首先,我假设此代码在控制器中。我强烈建议您避免在控制器上添加查询,而是use repositories。
我认为发生此错误是因为您之前未通过参数收到类别ID。这样就可以了:
$dm = $this->get('doctrine')->getManager();
//This gets the object from db
$category = $dm->getRepository('CarsCarsBundle:Category')->findOneById($categoria);
if ($category !== null) {
$posts = $dm->getRepository('CarsCarsBundle:Post')->findOneByCategory($category);
} else {
//The id received is not on the db.
}