How and where to execute custom queries in symfony 4?

Member

by dana , in category: PHP Frameworks , a month ago

How and where to execute custom queries in symfony 4?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a month ago

@dana 

In Symfony 4, you can execute custom queries using Doctrine QueryBuilder or Doctrine DBAL.

  1. Using Doctrine QueryBuilder:
  • In your controller or service, inject the EntityManagerInterface class.
  • Inside the method or function, create a query using the QueryBuilder instance:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
use DoctrineORMEntityManagerInterface;

// ...

class MyController extends AbstractController
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function myAction()
    {
        $queryBuilder = $this->entityManager->createQueryBuilder();

        $query = $queryBuilder
            ->select('u')
            ->from(User::class, 'u')
            ->getQuery();

        $result = $query->getResult();
        
        // Handle the query result
    }
}


  1. Using Doctrine DBAL:
  • In your controller or service, inject the Connection class.
  • Inside the method or function, create a query using the Connection instance:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
use DoctrineDBALConnection;

// ...

class MyController extends AbstractController
{
    private $connection;

    public function __construct(Connection $connection)
    {
        $this->connection = $connection;
    }

    public function myAction()
    {
        $sql = "SELECT * FROM my_table";
        
        $result = $this->connection->executeQuery($sql)->fetchAll();
        
        // Handle the query result
    }
}


Note: Replace User::class with your desired entity class and my_table with your actual table name.


Executing custom queries in Symfony 4 can be done in controllers, services, or repositories, depending on your project's architecture and requirements.