简体   繁体   中英

ZF2 Doctrine Hydratation

When I query a table, for example:

$query  = $this->entityManager->createQueryBuilder();
$query->select('TaPost')->from("Application\Entity\TaPost", 'TaPost'); 
return $query->getQuery()->getResult()
)

I get an array of object "Tapost".

Is there an easy way (and not ruining performance) to get an array of a given new class ? An equivalent to zend/db/sql:

new HydratingResultSet(new \Zend\Stdlib\Hydrator\ClassMethods(), new myNewClass())

Do you want to get directly array result? There are two way. You get an entity object which is \\Application\\Entity\\TaPost . You can create a method to your entity like that

class TaPost {
    // Your entity attributes and methods
    // ...

    public function toArray()
    {
        return array(
                "id" => $this->getId(),
                "title" => $this->getTitle(),
                "description" => $this->getDescription(),
                // ...
            );
    }
}

And use them them when your for loop.

Another solution is, you can use Doctrine HYDRATE_ARRAY

$results = $query->getQuery()->getResult( Doctrine\ORM\Query::HYDRATE_ARRAY );

Try to use doctrine hydrator instead of zend hydrator.

$model = new \Blog\Model\Post();
$hydrator = new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($this->getEntityManager(), 'Blog\Model\Post');
$model = $hydrator->hydrate($array, $model);

thank you for your answer but that's not exactly my objective. I'm trying to do the tutorial and, instead of zend-db-sql i'm using Doctrine.

I have a method findAll() which have to return an array of objects from class PostInterface based on a custom model (post). With Doctrine, I get an array of TaPost ( TaPost being an entity of Doctrine) but I need to return an array of Post .

How can I tell Doctrine to automatically hydrate Post and not TaPost ? will i need to made a foreach on my doctrine result and hydrate an object Post one by one ?

ps: with zned-sql, they do it when getting the result:

$resultSet = new HydratingResultSet(new \Zend\Stdlib\Hydrator\ClassMethods(), new \Blog\Model\Post());

return $resultSet->initialize($result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM