ZF2 - Iterating over a HydratingResultSet

时光怂恿深爱的人放手 提交于 2019-12-12 02:06:30

问题


I'm using TableGateway's selectWith function to return a HydratingResultSet of entities. I need to iterate through each of the entities of the result set - not sure how I'm to do it, but using a foreach gives the error "This result is a forward only result set, calling rewind() after moving forward is not supported".

What I was trying to do is basically:

$res = $this->tableGateway->selectWith($query);
foreach($res as $r) {...} 

What am I doing wrong? We're using Zend Framework 2.3. Thanks in advance!


回答1:


You have to buffer() result before itarate or get an array - toArray()

$res = $this->tableGateway->selectWith($query);

$res->buffer(); // you need to buffer result first
//$res = $res->toArray(); // or transform resultset to array but I prefere more to buffer

foreach($res as $r) {...} // first iterate 
foreach($res as $r) {...} // second iterate 

but be careful this isn't advisable on the large results.




回答2:


You are using $res before reaching the foreach loop...

HydratingResultSet is forward only result set(data has not been loaded from the database) and once you iterate throw it , you can't do it again.

to use the Resultset multiple times, you need to load all the data at once. $res->buffer() or $res = $res->toArray()

what code do you have between $res and foreach ???



来源:https://stackoverflow.com/questions/26752594/zf2-iterating-over-a-hydratingresultset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!