7

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?

1
  • At the end, I've worked with entity and stop... Thanks everyone! Commented Jun 26, 2017 at 14:37

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey @matko, you have a typo on the word function.
3

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.