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

Fetch Records as array of Objects instead of ResultSet\Simple

Hey Guys!

I know, this question (or questions similar to this one) was already asked a couple of times. Unfortunatly none of those answering my question. So, what am I trying to do: I have a Model and want to fetch records from the related Database table. This looks like this (simplified example):

class RobotsRepository
{
    public function find()
    {
        $robot = Robot::find([
            'hydration' => Resultset::HYDRATE_OBJECTS
        ]);

        return $robots;
    }
}

But, what I actually want to return is an array of Robot objects, not an useless (sorry) ResultSet-class. I'm really into the declaration of variables with there type and since PHP7 increased support for it, I'm basically doing this all the time in all methods. And for me it is simply not practical to sometimes have a ResultSet\Simple object and sometimes an array of objects.

So, please tell me there is an easy way to achieve the goal, any help would be very much appreciated. PS: No, doing a toArray() call to have no models is not really an option. There is this magic thing called autocompletion I want to use ;)

Thanks in advance & Best Chris

Hi Christoph you have to use iterator_to_array()


    <?php
    class RobotsRepository
    {
      /**
      * @return Robot[]
      */
      public function find(): array
      {
        $robots = Robot::find([
        'hydration' => Resultset::HYDRATE_OBJECTS
        ]);

        return iterator_to_array($robots);
        }
    }

This way you transform a Resultset\Simple in Robot's array

Good luck

Thank you so much! This works out. Unfortunatly I marked my first (and now deleted) reply as accepted answer and now cannot mark yours :(

Hi Christoph you have to use iterator_to_array()


  <?php
  class RobotsRepository
  {
    /**
    * @return Robot[]
    */
    public function find(): array
    {
      $robots = Robot::find([
      'hydration' => Resultset::HYDRATE_OBJECTS
      ]);

      return iterator_to_array($robots);
      }
  }

This way you transform a Resultset\Simple in Robot's array

Good luck