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

Phalcon\Mvc\Model::toArray and Phalcon\Mvc\Model\Resultset\Simple::toArray

Hello, I have a Model with a hasMany relation, I have an instance of such record and need to get the related objects as an array with a subset of columns. Since this relation is a type of Phalcon\Mvc\Model\Resultset\Simple I can obtain the result wanted invoking toArray, unfortunately this method has not the capability of Model::toArray (it returns a subset of columns passed as array in the first parameter), how can I do to obtain such result? do a custom foreach and invoke toArray on each model and push to an array or is there another way?

This appears to me as an inconsistency between two methods where Resultset::toArray should be a natural 'extension' of Model::toArray.

thx.



33.8k

You mean a N:M relationship? Maybe with a foreach ($model->theOtherModel as $theOtherModel). Didn't work with that type of relationships yet, and don't know if it is exactly what you want, but I hope it will help.



7.3k
edited Aug '14

Hi, thx for the reply but what I really mean is this: If I have a Person with columns: Name, Surname and Age and I have a single instance from database (ex: got with findFirst or other means) I can use toArray to obtain an array of such columns or part of these es:

$personobj->toArray() => [name, surname, 20]

I can also filter for certain columns:

$personobj->toArray(array('Name', 'Age')) => [name, 20]

When I get a Resultset\Simple of 2 or more Person I can use toArray too, method is exposed by Simple itself:

$results->toArray() => [ [name1, surname1, 20], [name2, surname2, 21], ..... [name-n, surname-n, 2xx], ... and so on... ]

What I can't do is:

$results->toArray(array('Name', 'Age')) to get => [ [name1, 20], [name2, 21], ..... [name-n, 2xx], ... ]

because toArray of Simple doesn't accept first (and only) argument as array of column, insted it accept [boolean $renameColumns]

https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Model.html vs https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Model_Resultset_Simple.html

As I said, this seems a bit odd.



33.8k

Mmmm... did you try that toArray? Maybe it only would do a [ 'firstResult' => [name, surname, 20] ]. I mean:

$results->toArray(true)->toArray(array('Name', 'Age'))

I'm sure that it will not work, but xD

But yeah, it is odd. So if the said before doesn't work, you'll need to do a foreach I think. Also you could try to do a pull fixing that (if Phalcon doesn't have problems with it), or find a way to convert its columns to an array after toArray (I can't help much more, I'm so noob with this things haha).