我想从 zend 2 中访问 doctrine 2 DBAL 以进行本机 sql 查询

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

我在我的网站上使用 zend 2 和 doctrine 2。但是我想进行原生 sql 查询,因此需要 mysql 连接。

我知道学说 2 通过 DBAL

我指的是马克·罗宾逊 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');

我可以通过以下方式访问我的实体管理器;

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

您可以 运行 使用您的 EntityManagerResultMapping 实例的本机查询,如下所示:

use Doctrine\ORM\Query\ResultSetMapping;

$rsm = new ResultSetMapping();

$entityManager = $htis->getEntityManager();
$query = $entityManager->createNativeQuery(
    'SELECT id, name, discr FROM users WHERE name = ?', $rsm
);
$query->setParameter(1, 'romanb');

$users = $query->getResult();

来了straight from the documentation of Doctrine 2

但您也可以使用更多原生解决方案,例如 DQL or use the EntityManager directly to find objects

不太确定问题到底在问什么。您可以使用与获取实体管理器相同的方法。只需要更改服务ID:

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

顺便说一句,使用局部变量来缓存结果可能是一种代码浪费。只需在需要时从服务定位器中提取即可。

或者,如果您已经有了实体管理器,那么一个简单的:

$connection = $entityManager->getConnection();

可能想要了解一下 dbal 连接对象的实际含义以及如何使用它。

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