Raw SQL Execution with Doctrine 2
To manipulate database tables effectively, executing raw SQL commands becomes necessary at times. For instance, if you need to truncate tables and initialize them with default data.
Solution
Doctrine 2 enables you to run raw SQL queries using its EntityManager interface. Here's an example that showcases this functionality:
<code class="php"><?php namespace Acme\SportBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Doctrine\ORM\EntityManagerInterface; class AuthoritativeSportsRecordsController extends AbstractController { public function getAuthoritativeSportsRecords(EntityManagerInterface $em) { $sql = " SELECT name, event_type, sport_type, level FROM vnn_sport "; $stmt = $em->getConnection()->prepare($sql); $stmt->execute(); return $stmt->fetchAll(); } }</code>
In this example, we execute a raw SQL query to retrieve data from the "vnn_sport" table. The query can be modified to suit your specific needs, such as truncating or initializing tables. Remember to replace "vnn_sport" with the name of your target table.
The above is the detailed content of How to Execute Raw SQL Queries with Doctrine 2?. For more information, please follow other related articles on the PHP Chinese website!