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

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.



98.9k

Try setting up an hydration mode:

https://docs.phalcon.io/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.



2.5k
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);

LOL

5 years later in a far distant galaxy...

A case of use is this: https://forum.phalcon.io/discussion/18089/resultset-as-many-to-many-relation-value-issue

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