Reputation: 1828
If I use this method to retrieve data I cannot parse it in my PHP like this $data[0]['string']
. PHP just says this is an Object
and it cannot parse it as Array
error message
Cannot use object of type App\Entity\MyEntity as array
Controller code:
$data = $this->em
->getRepository(Myclass::class)
->findBy(['foo' => $var]);
How can I return a parsable array from a simple findBy()
directly from the controller without having to go through the Repository and QueryBuilder with ->getArrayResult()
?
Upvotes: 0
Views: 1792
Reputation: 4582
All you need to do is to create your custom function in your repository:
public function findItByFoo($var){
$qb = $this->createQueryBuilder('myClass');
$qb->select("myClass")
->where('foo = :var')
->setParameter('var', $var);
$result = $qb->getQuery()->getArrayResult();
return $result;
}
You cannot achieve this with built-in findBy method. More specifically, the findBy definition is:
$repository->findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null);
As you can see for yourself there is not any argument for the hydration mode.
Finally, since you want to hydrate your entities as arrays instead of objects, and you want to do that in your controller, the only solution is something like this:
$data = $this->em->getRepository(Myclass::class)->createQueryBuilder('m')
->select("m")->where('foo = :var')->setParameter('var', $var)
->getQuery()->getArrayResult();
As you can see, it almost identical with the code in the findItByFoo() function I wrote above, I just wanted to mark that you can do that also in your controller (even not suggested, programmatically speaking).
Upvotes: 2