How to Execute Raw SQL Queries with Doctrine 2?

Mary-Kate Olsen
Release: 2024-10-27 09:05:30
Original
1006 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!