自Doctrine DBAL 2.13 以来,这里的大多数答案现在都已弃用。例如,execute is deprecated and fetchAll will be removed in 2022。
/**
* BC layer for a wide-spread use-case of old DBAL APIs
*
* @deprecated This API is deprecated and will be removed after 2022
*
* @return list<mixed>
*/
public function fetchAll(int $mode = FetchMode::ASSOCIATIVE): array
不再推荐使用execute,然后是fetchAll,因为两者都已弃用。
* @deprecated Statement::execute() is deprecated, use Statement::executeQuery() or executeStatement() instead
* @deprecated Result::fetchAll is deprecated, and will be removed after 2022
所以在执行原始 SQL 和获取结果时,我们必须更加具体。
我们需要使用executeQuery 或executeStatement,而不是使用Statement::execute()。
executeQuery 返回对象Result:
使用当前绑定的参数执行语句并返回
结果。
executeStatement返回int:
使用当前绑定的参数执行语句并返回受影响的行。
我们需要使用fetchAllNumeric 或fetchAllAssociative (and more),而不是使用Result::fetchAll()。
要获得简单的结果,您必须这样做:
public function getSqlResult(EntityManagerInterface $em)
{
$sql = "
SELECT firstName,
lastName
FROM app_user
";
$stmt = $em->getConnection()->prepare($sql);
$result = $stmt->executeQuery()->fetchAllAssociative();
return $result;
}
并带有参数:
public function getSqlResult(EntityManagerInterface $em)
{
$sql = "
SELECT firstName,
lastName,
age
FROM app_user
where age >= :age
";
$stmt = $em->getConnection()->prepare($sql);
$stmt->bindParam('age', 18);
$result = $stmt->executeQuery()->fetchAllAssociative();
return $result;
}