简体   繁体   中英

How to fetch results one by one in Doctrine 1.2?

How can I make something similar to classic PHP PDO

while ($obj = $stmt->fetch()) {...}

in Doctrine 1.2.

I've tried

while ($obj = $query->fetchOne()) {...} 

but it returns always only the first object found.

Is there any way I could implement this behaviour?

Doesn't really matter my query. It's a plain simple one (note that I am in the *Table class of the model)

$query = $this->createQuery('a');

While working on a migration command in symfony2 I discovered that $query->executes(); fetches the complete result set into RAM before returning it.

This is not a problem with a small amount of data, but with bigger results your process might run OutOfMemory.

To solve the problem you can iterate through the results "one by one" with this statement:

$query->iterate();

I thing its similare to this PDO statement: while ($obj = $stmt->fetch()) {...}

A more complete example might look like this:

$em = $this->getContainer()->get('doctrine');
$iterator = $em->getRepository('AcmeBundle:Entity')
               ->createQueryBuilder('e')
               ->getQuery()->iterate();

foreach($iterator as $item){
   $item = $item[0];

   // Your logic here:
   $item->getId();
   ....       
}

Found this in the doctrine documentation .

Have you tried:

while ($obj = $query->execute()) {...}

And if you want to fetch an array instead of objects:

while ($obj = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY)) {...}

If you got the connection, do it like this:

$stmt = $conn->query($queryString);
while ($obj = $stmt->fetch()) {...} 

With fetchOne() you will only get one entry at all.

Use the hydrate mode Doctrine_Core::HYDRATE_ON_DEMAND

$q = Doctrine_Query::create()
                ->select('...')
                ->from('...');

// Returns instance of Doctrine_Collection_OnDemand
$result = $q->execute(array(), Doctrine_Core::HYDRATE_ON_DEMAND);
foreach ($result as $obj)
{
    // do something with your object
}

More information : Data Hydrators — Doctrine 1.2.4 documentation

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