phpzend-frameworkdoctrine

Alternative for fetchAllAssociative()` and execute in doctrine


I am calling a stored procedure using native sql via doctrine. fetchAllAssociative() and execute are deprecated. What are the alternatives?

    $sql = 'CALL spWithParams(:param)';
    $stmt = $this->getEntityManager()->getConnection()->prepare($sql);
    $stmt->execute([":param"=>"test"]);
    print_r($stmt->fetchAllAssociative());

I am not planning to map the response to entity using ResultSetMapping() as mentioned here as I will add my custom wrapper on it.


Solution

  • The right way of doing this is to use a ResultSetMapping with scalar results to select arbitrary fields. You can then execute the query with getArrayResult() to achieve the same behaviour as in the provided code.

    As an example:

    $rsm = new ResultSetMapping();
    $rsm->addScalarResult('my_database_column', 'myField');
    $query = $this->getEntityManager()->createNativeQuery(
        'CALL spWithParams(:param)',
        $rsm
    );
    $query->setParameters([":param"=>"test"]);
    
    $results = $query->getArrayResult();
    /* 
    [
      ['myField' => 'foo'],
      ['myField' => 'bar']
    ]
    */