Get objects array instead of ResultSet object from QueryBuilder result

Hi,

How can I get an array of objects instead of a ResultSet object from QueryBuilder execute method?

The toArray method doesn't suit me because it converts the ResultSet into an array of arrays and I want an array of objects.

Thank you.



82.7k

Try setting up an hydration mode:

http://docs.phalconphp.com/en/latest/reference/models.html#hydration-modes

$robots = $this->modelsManager->createBuilder()
    ->from('Robots')
    ->where('name = :name:')
    ->andWhere('type = :type:')
    ->getQuery()
    ->execute(array('name' => $name, 'type' => $type))
    ->setHydrateMode(Resultset::HYDRATE_ARRAYS);

foreach ($robots as $robot) {
  echo $robot['name'];
}

No, that's is not what I want... I would like to be able to do this:

$robots = $this->modelsManager->createBuilder()
    ->from('Robots')
    ->where('name = :name:')
    ->andWhere('type = :type:')
    ->getQuery()
    ->execute(array('name' => $name, 'type' => $type))
    // maybe a new type of hydration ?!?
    ->setHydrateMode(Resultset::HYDRATE_ARRAY_OF_OBJECTS);

// $robots return should be an array

foreach ($robots as $robot) {
  echo $robot->name;
}

The ResultSet object is iterable in some ways like an array (ie: foreach(), count()). Just curious what you need an array for?

I need to merge two or more result arrays.



1.8k
edited Sep '15

@hugoduraes

$robots1 = $this->modelsManager->createBuilder()
    ->from('Robots')
    ->where('name = :name:')
    ->andWhere('type = :type:')
    ->getQuery()
    ->execute(array('name' => $name, 'type' => $type))
    ->setHydrateMode(Resultset::HYDRATE_ARRAYS)
    ->toArray();

$robots2 = $this->modelsManager->createBuilder()
    ->from('Robots')
    ->where('name = :name:')
    ->andWhere('type = :type:')
    ->getQuery()
    ->execute(array('name' => $nameOther, 'type' => $typeOther))
    ->setHydrateMode(Resultset::HYDRATE_ARRAYS)
    ->toArray();

$result = array_merge($robots1, $robots2);