问题
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