Home  >  Article  >  Backend Development  >  How to Execute Raw SQL Queries with Doctrine 2?

How to Execute Raw SQL Queries with Doctrine 2?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 09:05:301007browse

How to Execute Raw SQL Queries with Doctrine 2?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn