Using native SQL query without entity class Using native SQL query without entity class symfony symfony

Using native SQL query without entity class


Do you have a particular need to map results to a domain object? If not, you could use the DBAL to make a plain old query, which will return an array, as detailed in the Symfony2 cookbook and the Doctrine DBAL documentation:

$conn = $this->container->get('database_connection');$sql = 'SELECT res.id, COUNT(*)...';$rows = $conn->query($sql);


Use addScalarResult method of ResultSetMapping

$rsm = new ResultSetMapping();$rsm->addScalarResult('cnt', 'cnt');$rsm->addScalarResult('id', 'id');$query = $this->em->createNativeQuery('SELECT count(*) AS  cnt, id_column as id FROM your_table group by id', $rsm);$result = $query->getResult();var_dump($result);

Result array:

array (size=1)  0 =>     array (size=2)      'cnt' => int 1      'id' => int 15