Symfony 2.8:显示数组收集的DQL查询

时间:2016-02-08 09:53:58

标签: doctrine-orm dql doctrine-query

我是Symfony 2的初学者,我遇到DQL查询问题:我正在尝试显示一个ArrayCollection属性。

这是我的情况:两个类与“ManyToOne”和“OneToMany”连接在一起

DishGrade.php:

/**
* @var Dish $dish
*
* @ORM\ManyToOne(targetEntity="Dish", inversedBy="grades", 
cascade={"persist", "remove", "merge"})
* @ORM\JoinColumn(name="dish_id", referencedColumnName="id", nullable=false)
*
*/
private $dish;

Dish.php:

/**
* @var \Doctrine\Common\Collections\Collection $grades
*
* @ORM\OneToMany(targetEntity="DishGrade", mappedBy="dish", cascade={"all"},
orphanRemoval=true)     
*/
private $grades;

然后这是我的控制器,它返回一个对象数组“DishGrade”

/**
* Get grades dish.
*
*
* @ApiDoc(
*   output = "Awadac\ApiBundle\Model\Dish",
*   statusCodes = {
*     200 = "Returned when successful",
*     404 = "Returned when the dish is not found"
*   }
* )
*
* @Get("/dishes/{id}")
*
* @param Request $request the request object
* @param int     $id      the dish id
*
* @return array
*
* @throws NotFoundHttpException when dish not exist
*/
public function getDishAction(Request $request, $id)
{
$dish = $this->getDishManager()->getRepository()->getGrades($id); 

if (!$dish) {
    throw $this->createNotFoundException('Dish does not exist.');
}
return $dish;
}

这是我的查询不起作用:

DishRepository.php:

public function getGrades($id){


$qb = $this->_em->createQueryBuilder();

return $qb->select('d.grades')
    ->from('AwadacApiBundle:Dish', 'd')
    ->where('d.id = :id')
    ->setParameter('id', $id)
    ->getQuery()
    ->getResult();


 }

我得到的错误代码:

{“code”:500,“message”:“[语义错误]第0行,第9行附近'成绩来自AwadacApiBundle:菜':错误:无效的PathExpression。必须是StateFieldPathExpression。”,“errors”:null }

当我想从我的对象“Dish”中获取所有属性时,它可以工作,所以我只是想知道为什么我不能单独显示这个ArrayCollection。

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

如果您已经在DishRepository中,则可以通过

创建查询构建器
$qb = $this->createQueryBuilder('d');

进一步删除 - > from()语句,我想它应该可以正常工作:

return $qb->select('d.grades')
        ->where('d.id = :id')
        ->setParameter('id', $id)
        ->getQuery()
        ->getResult();