Friday, December 5, 2008

How to make native SQL queries in Doctrine ORM

Sometimes you have situation which require writing of native SQL query in project fully based on Doctrine ORM. Doing DQL queries is very easy, but simple SQL queries maybe difficult to execute because you have to reuse database connection opened inside Doctrine.

Example given below is easy to understand and use in your project(s). Enjoy!
// get Doctrine_Connection object
$con = Doctrine_Manager::getInstance()->connection();
// execute SQL query, receive Doctrine_Connection_Statement
$st = $con->execute("...............");
// fetch query result
$result = $st->fetchAll();

9 comments:

Carlos Eduardo da Fonseca said...

Thanks man, you saved my life!!!

Jason said...

Thanks a lot. Doctrine's documentation is not very good. Ive been looking for this for a couple of day.

okan said...

Great job!But I need to get dataset as Doctrine_Query Object.How can I do that?

Yuri Subach said...

okan, I think you can do the following. For each array in the result set: create your object manually (like $user = new User()) and populate it with your data $user->fromArray().

Boyd said...

okan

look here in the manual (http://www.doctrine-project.org/documentation/manual/1_2/en/native-sql#component-queries) I think this is what you are looking for.

okan said...

Thank you guys!

Husni said...

Thank you very much.. this is very useful.

jmmm said...

I use your snippet to create a table with native SQL after a data load task thanks to the command_post listener.

Unfortunately, i have an error, wich is an hydratation error i guess. The returned error code looks like that :

SQLSTATE[HY000]: General error

Cansomeone help me ? Thanks in advance

Yuri Subach said...

jmmm

it'd hard to say what's wrong without sources and other error details.