Reputation: 1054
How can I handle a raw sql in symfony 2 which return an Object of a entity?
I need this for using it withing reflectionMethods (invoke) which only works with Object.
Actually I recieve an array:
stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->prepare('SELECT '.$neededColumns.' FROM Data '.$sql);
$stmt->execute();
$result= $stmt->fetchAll();`
Can I use
$items = $stmt->fetchAll(\PDO::FETCH_CLASS, "NameOfBundle\Entity\Content");
I stuck so it would be great to get some help from yourside.
Upvotes: 2
Views: 3013
Reputation:
If you have access to the Doctrine registry (which is the $this->getDoctrine()
call that you're making) then you'll want to look into the Native SQL feature of Doctrine ORM.
The documentation is fairly extensive but your code will probably look something like:
$em = $this->getDoctrine()->getEntityManager();
$rsm = new ResultSetMappingBuilder($em);
$rsm->addRootEntityFromClassMetadata('NameOfBundle\Entity\Content', 'alias');
$selectClause = $rsm->generateSelectClause([ 'alias' => 'table_alias' ]);
$sql = 'SELECT '.$selectClause.' FROM table table_alias';
$query = $em->createNativeQuery($sql, $rsm);
$object = $query->getOneOrNullResult();
Obviously the $sql
part can be whatever SQL you want, but if you need joined entities then be sure to use $rsm->addJoinedEntityFromClassMetadata()
method, again, explained within the documentation.
Upvotes: 4