So, it seems like you are in big trouble. Otherwise, why will you want to execute a doctrine native SQL query? In this tutorial, I will describe and show how you can perform such operations. But that doesn’t necessarily mean I am encouraging you to use it all the time. I will still strongly recommend finding your way within the doctrine’s ORM, DBAL And DQL implementation as much as possible. However, you may face some UN-avoidable situations where you can’t help without native SQL support, as I faced recently.
My Scenario For Choosing Doctrine Native SQL Query Support:
My application was in a stable database schema/entity implementation and was live. For refactoring purposes, I had to change entities in DB schema for adding/removing columns/properties. Now, as the application is live, I need to transfer all my old data to the new schema, thus needing a bulk migration script. Here is what I could do – retrieve data from the old database, process them accordingly and insert them into the new database table(s). But did you notice we changed our entities per the new schema and thus can’t retrieve data from the old database in ORM style?
Hmm, so, now what? Well, here is what came into my mind to use the doctrine native SQL query support. Using this, after retrieving data from the old database, we can either insert/process them as a new entity or in native support, what suits best for the requirement.
This is not the only case where we may face similar issues; you may find others as well. For the sake of such a scenario, let’s go and learn the basics.
Getting Database Connection From Entity Manager:
The first step to using doctrine is to get the connection object from the entity manager. Let’s see the basic initialization of the doctrine entity manager and retrieving connection instance in PHP:
As you are possibly using doctrine already, you can skip initialization. Best way to use them as a separate wrapper class for your application as the one I showed before while integrating doctrine with codeigniter.
//**********priliminary doctrine set up. You can do it separate generalized class/function as well********
$config = new \Doctrine\ORM\Configuration;
// Cache Setup
$apcCache = new \Doctrine\Common\Cache\ApcCache;
$config->setMetadataCacheImpl($apcCache);
$config->setQueryCacheImpl($apcCache);
$config->setResultCacheImpl($apcCache);
// Proxy Setup
$config->setProxyDir('proxy');
$config->setProxyNamespace('Proxies');
$config->setAutoGenerateProxyClasses(true);
// Mapping Setup
$driverImpl = $config->newDefaultAnnotationDriver(__DIR__);
$config->setMetadataDriverImpl($driverImpl);
// Connection Setup
$connectionOptions = array(
'dbname' => "database_name",
'user' => "db_user_name",
'password' => "db_password",
'host' => "db_host",
'driver' => 'pdo_mysql');
// Initialize Entity Manager
$entityManager = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
//**** Basic Initialization Ends Here*********//retrieve the connection object
$connection = $entityManager->getConnection();Code language:PHP(php)
Prepare And Execute SQL Query:
there is a helpful method named ‘prepare’ which will help us to create an SQL statement suitable for execution under Doctrine. Then, the generalized ‘execute’ method will run the SQL query, whether it’s “insert”/”delete”/”update” or a select statement. Following is the code snippet example:
$statement = $oldConnection->prepare("SELECT * FROM mytable");
$statement->execute();Code language:PHP(php)
Now, if the query is of insert/update or delete, we should be done and fine. But in the case of a select query, we need to fetch the data, which should be something like as below:
//fetch all results in associative array format
$results = $statement->fetchAll();
//fetch single row
$result = $statement->fetch();
//total row count
$result = $statement->rowCount();Code language:PHP(php)
Friendly Support For CRUD Operations:
As we have seen, we can now run the raw SQL query; we can use some more friendly methods for database update operations, which are directly applied on the connection object. Let’s see few examples:
//insert data from an associative array
$connection->insert('table_name', $associative_array);
//update row from an associative array
$connection->update('table_name', $associative_array,$identifier);
//delete a row
$connection->delete('table_name', $identifier);Code language:PHP(php)
Running Transaction In Doctrine Native SQL Query Mode:
You may sometimes need to run multiple queries in a single transaction to optimize the database operations. As you can see above, in my case, optimization is crucial. Thus I needed a way to do such operations to reduce the total number of database connectivity and make the process faster. You might need it for other purposes like rollback if some operations failed etc cases as well. Let’s see some code examples of how they can be achieved:
The above example is for insert operation, though you can use it for update/delete or ‘execute’ method etc as well too.
Final Words:
Hopefully, this small tutorial on doctrine native SQL query support will be helpful for you in some situations. Read more on doctrine documentation on this topic as further reference. Let me know if you are facing any issues while trying the PHP code examples above. Happy coding 🙂
Thanksssssssssssssssssssssssssssssssssa lot brother you don’t know how it could help me ! BDW thank you sooo much !! i just got logic and edited my query ! after 4hrs i found solution from ur blog ! (Y) appreciated !
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
Mr JiJo says
Thanksssssssssssssssssssssssssssssssssa lot brother you don’t know how it could help me ! BDW thank you sooo much !! i just got logic and edited my query ! after 4hrs i found solution from ur blog ! (Y) appreciated !