Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using native SQL query without entity class

I need to create native SQL query with couple of unions and subqueries. It'll look approximately like this:

SELECT res.id, COUNT(*) as count_ids FROM (     SELECT a.id FROM ... a WHERE ... LIKE ('%:param%')     UNION ALL     SELECT b.id FROM ... b WHERE ... LIKE ('%:param%')     UNION ALL     ... ) res GROUP BY res.id ORDER BY count_ids asc 

Result won't match any Entity I use in my application. Is it possible to create ResultSetMapping with "anonymous" object? Or is it, at least, possible to create an Entity that wouldn't create table next time I update schema, so I can map results to it?

Or is there any other Doctrine-friendly way to deal with such query? Making changes to database isn't possible though, as I'm dealing with legacy stuff that cannot be touched. I'd also strongly prefer if I did everything on database side, not involving much of PHP in it.

like image 484
Ondrej Slinták Avatar asked Jul 28 '11 14:07

Ondrej Slinták


People also ask

What is native SQL query?

Native SQL is the SQL that the data source uses, such as Oracle SQL. Use Native SQL to pass the SQL statement that you enter to the database. IBM® Cognos® Analytics may add statements to what you enter. You can not use native SQL in a query subject that references more than one data source in the project.

What is the difference between JPQL and native query?

There are three basic types of JPA Queries: Query, written in Java Persistence Query Language (JPQL) syntax. NativeQuery, written in plain SQL syntax. Criteria API Query, constructed programmatically via different methods.


Video Answer


1 Answers

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); 
like image 158
Derek Stobbe Avatar answered Sep 21 '22 13:09

Derek Stobbe