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

Change object field while iterating Resultset

Lets assume, we have a code, and we need to change robot's name in cycle:

$robots = Robots::find(array("type='virtual'", "order" => "name"));
foreach($robots as $robot){
  $robot->name = rand(1,10)
}

Objects do not actually change. If I do next cycle with resultset - all objects will have original values. I understand that Resultsets are immutable. Isn't it?

Is there is a possibility to change model objects while iterating through resultset? Or I need to find workarounds to solve my task?

P.S. I don't need to save this changes in database, so "->update" does not fit

Originally in 'foreach' you can't change value in cycle (coz it's iterator issue)... this case is common for most all compiled languages... I don't know all cases of Phalcon... but it seems that you can only create new array for this objects...



98.9k

Every object returned by the iterator is not attached to the iterator, this reduces the memory usage when traversing resultsets with a large number of records in it. You can override the find method to return an array instead of a resultset:

<?php

class Robots extends Phalcon\Mvc\Model
{
    public static function find($params=null)
    {
        $rows = array();
        $result = parent::find($params);
        foreach ($result as $result) {
            $rows[] = $result;
        }
        return $rows;
    }
}

Ok, thank you.