Claudio Ɯǝıs Mulas
Claudio Ɯǝıs Mulas

Reputation: 1113

Symfony 3, query without Entity but with doctrine

I've created an API system. Everything is perfect, it works with Elastic as Db. Unfortunately a single function need to add/edit/retrieve a row in an old mysql db.

I don't want to connect to db anytime but just when I need it. I'd like to use createQueryBuilder but without entity. Is it possible?

Upvotes: 7

Views: 17595

Answers (3)

Matko Đipalo
Matko Đipalo

Reputation: 1776

You could use the DBAL to make a plain old query, which will return an array:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

class MyRepository extends EntityRepository
{
    public function findSmth()
    {
        $conn = $this->getEntityManager()->getConnection();
        $sql = 'SELECT * FROM my_table';
        $stmt = $conn->prepare($sql);
        $stmt->execute();

        var_dump($stmt->fetchAll());die;
    }
}

QueryBuilder just converts down to DQL, and DQL provides querying capabilities over your object model. So, I think you cannot use QB without entity.

Upvotes: 15

ste
ste

Reputation: 1529

Sure, it's documented here

http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/query-builder.html

  1. SQL Query Builder

Doctrine 2.1 ships with a powerful query builder for the SQL language. This QueryBuilder object has methods to add parts to an SQL statement. If you built the complete state you can execute it using the connection it was generated from. The API is roughly the same as that of the DQL Query Builder.

You can access the QueryBuilder by calling Doctrine\DBAL\Connection#createQueryBuilder

From inside a controller I think you should work on $this->getDoctrine()->getManager()->getConnection()->createQueryBuilder() and fire your raw SQLs

Upvotes: 1

Max P.
Max P.

Reputation: 5679

You can add new connection to doctrine config:

config.yml

....
doctrine:
    dbal:
        default_connection: default

        connections:
            default:
                ...
            old_mysql_db
                driver:   pdo_mysql
                host:     127.0.0.1
                port:     3306
                dbname:   dbname
                user:     user
                password: password
    orm:
        ...
...

And use this connection in controllers

...
$conn = $this->getConnection('old_mysql_db');
$qb = $conn->createQueryBuilder(); // \Doctrine\DBAL\Query\QueryBuilder
...

Doctrine connects to DB on first sql-query that uses this DB.

Upvotes: 3

Related Questions