We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Iterating a ResultSet

It seems that whenever the same instance of ResultSet is repeatedly iterated, it recreates the Model instances every time.

For the sake of example, here I'm looping over a ResultSet to change the "name" property of every Model instance. However the next loop prints the original value instead of the changed one.

// get the ResultSet
$childList = $this->getChildNodes();

foreach ($childList as $child)
{
    $child->name = 'boo';
}

foreach ($childList as $child)
{
    var_dump($child->name);
}

if I replace the first line with this, then it works:

$childList = array();
foreach ($this->getChildNodes() as $child)
{
    $childList[] = $child;
}

Perhaps there's something I'm doing wrong?



98.9k

Phalcon does not keep records in memory, they're traversed one-by-one, so only one is kept in memory at time, imagine you're traversing a big resulset with thousands (or millions) of records, keeping all them in memory could be a waste of memory. Adding them as items of an array (as you do) increase their memory reference count so they are not removed from memory but this is something the developer must decide.

Thanks for explaining, it's kind of what I suspected. It would be nice to have a more persistent ResultSet though, there are plenty of situations when I'm working with predictably small ResultSets where the same Model instance could be referenced multiple times, while it's being processed, etc - but perhaps that's something that I can implement myself.

You could play with this: https://docs.phalcon.io/en/latest/reference/models.html#hydration-modes

//Return every robot as an stdClass $robots->setHydrateMode(Resultset::HYDRATE_OBJECTS);