Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get array of rows from DB without specifying columns in Symfony

I want to have Repository class that can execute every ‘SELECT’ query
that I enter in it, random query from outside.
And I dont want to specify columns that I want to get from this native query.

Usually, everybody would use this code :

$sql = 'select column_one, column_two from table';

$rsm = new ResultSetMapping();
$rsm->addScalarResult('column_one', 'columnOne');
$rsm->addScalarResult('column_two', 'columnTwo');

$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$result = $query->getResult();

But in my case I can’t specify ‘column_one’ or ‘column_two’,
because sql query and columns will be different.
And without $rsm->addScalarResult(‘column_one’, ‘columnOne’) I don’t get any results.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I get result without specifying columns

>Solution :

If you don’t want to have to configure a predefined result set, then you should do it like the example here: https://symfony.com/doc/current/doctrine.html#querying-with-sql

$conn = $this->getEntityManager()->getConnection();

$sql = '
        SELECT * FROM product p
        WHERE p.price > :price
        ORDER BY p.price ASC
        ';

$resultSet = $conn->executeQuery($sql, ['price' => $price]);

// returns an array of arrays (i.e. a raw data set)
return $resultSet->fetchAllAssociative();

I don’t think NativeQuery will work for your requirements because it relies on the idea of mapping the results to a known entity. If you don’t know anything in advance what the query is going to be, then you can’t do that mapping.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading