Using Views with Doctrine
Posted on
I've seen a few requests recently on how you can use a view with Doctrine. This is very easy and I've also learned a few neat tricks that you can do to accomplish abnormal things while writing this article.
Creating the View
First I will demonstrate how you can turn a normal Doctrine_Query
instance in to a view. This is just as easy as creating an instance of Doctrine_View
and setting a reference between the query and the view.
To create the view in the database you can call the Doctrine_View::create()
method.
Executing the View
Now when the Doctrine_Query
instance above is executed, it will execute the SQL for the view instead of parsing the DQL, generating the SQL and executing it.
Executing the above would execute the following SQL query.
Tweaking the View
Now here is where things get interesting. Say we wanted to take the SQL that the above Doctrine_Query
generates, and modify it slightly with some custom SQL that otherwise could not make it through the DQL parser.
We can get the SQL from the query, modify it, then manually create the view in our database.
The above would output the following SQL.
Now lets say we wanted to add something to the SQL that is proprietary to your DBMS, or is some complex SQL that won't make it through the DQL parser. We can modify the above SQL then re-create the view with that SQL manually. Let's make a simple change and add the USE INDEX
keyword to force MySQL to use a certain index for the query.
NOTE The example I have chosen is a very simple one only to demonstrate the capabilities. This example may not be a real world scenario for you. The only purpose of me showing this is to open a door for you to solve potential problems for you in the future.
Now lets take this query and manually create the view with it.
NOTE We must first drop the view as we already created it once in a previous step. This is just as easy as issuing the DROP VIEW command to MySQL. Afterward, re-create the view again with the modified SQL.
Now when we execute the code in the first part of this article it will execute the view which contains the customized SQL.
That is it! Now you can easily use some custom SQL in your queries as views. The benefit of using a view is that it is easily reusable and it is much faster than executing a normal query in most cases.