Doctrine调用存储过程时fetchAllAssociative与execute的替代方案
适配弃用方法的替代方案
Doctrine DBAL从3.x版本开始逐步废弃了原Statement类的部分旧API,你对应的替换逻辑如下:
- 原
execute()方法替换为executeQuery(),参数传递逻辑保持不变 - 原
fetchAllAssociative()方法调整为从executeQuery()返回的Result对象中调用,方法名本身没有变化,只是调用链路变更
修正后的可运行代码
$sql = 'CALL spWithParams(:param)'; $connection = $this->getEntityManager()->getConnection(); // 直接用executeQuery执行预处理SQL,兼容存储过程调用场景 $result = $connection->executeQuery($sql, [":param"=>"test"]); // 直接从Result对象获取关联数组结果 print_r($result->fetchAllAssociative());
可选写法(保留prepare预处理步骤)
如果你需要保留先预处理再传参执行的逻辑,也可以用如下实现:
$sql = 'CALL spWithParams(:param)'; $stmt = $this->getEntityManager()->getConnection()->prepare($sql); $result = $stmt->executeQuery([":param"=>"test"]); print_r($result->fetchAllAssociative());
上述实现完全不需要用到ResultSetMapping做实体映射,你可以直接基于返回的关联数组结果封装自定义处理层。
内容的提问来源于stack exchange,提问作者Danyal Sandeelo
相关产品推荐
相关产品推荐

