Search code examples
doctrine-ormzend-framework2

i want to access doctrine 2 DBAL from within zend 2 for a native sql query


i am using zend 2 an doctrine 2 on my site. i want however to make a native sql query and therefore need a mysql connection.

i understand that doctrine 2 gives this via the DBAL

i refer to Mark Robison here

Doctrine 2 ORM uses the Doctrine 2 DBAL, which is a thin but useful wrapper around the PDO database layer. You can retrieve that from the service container (it's called "database_connection", and give it whatever SQL you want, CASE and all. e.g. in your controller

:

$dbal = $this->get('database_connection');
$stmt = $dbal->prepare('SELECT foo FROM bar WHERE baz = :baz');
$stmt->bindValue('baz', 'qux');

i am able to access my entity manager via;

public function getEntityManager()
        {
            if (null === $this->em) {
                $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
            }
            return $this->em;
        }

Solution

  • Not really sure what the question is actually asking. You can use the same approach that you used for getting the entity manager. Just need to change the service id:

    public function getConnection() {
      if (null === $this->conn) {
        $this->conn = $this->getServiceLocator()->get('database_connection');
      }
      return $this->conn;
    }
    

    By the way, using a local variable to cache the results is probably a waste of code. Just pull it from the service locator when you need it.

    Or, if you already have the entity manager, then a simple:

    $connection = $entityManager->getConnection();
    

    Might want to read up a bit on what the dbal connection object actually is and how to use it.

    http://doctrine-dbal.readthedocs.org/en/latest/reference/data-retrieval-and-manipulation.html