Search code examples
doctrine-ormdqldoctrine-query

Symfony 2.8 : DQL query to display an arraycollection


I'm a beginner on Symfony 2 and I have a problem with a DQL query : I'm trying to display a property that is an ArrayCollection.

Here's my case : Two classes joined together with a "ManyToOne" and "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;

Then here's my controller which returns an array of objects "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;
}

And here's my query that doesn't work :

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


 }

the error code I get :

{"code":500,"message":"[Semantical Error] line 0, col 9 near 'grades FROM AwadacApiBundle:Dish': Error: Invalid PathExpression. Must be a StateFieldPathExpression.","errors":null}

And when I want to get all the properties from my object "Dish" it works, so I just wonder why I can't display this ArrayCollection alone.

Thank you for your time !


Solution

  • If you are already in the DishRepository you will be able to create the query builder by

    $qb = $this->createQueryBuilder('d');
    

    Further just remove the ->from() statement and I guess it should work properly:

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