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

array convert to Phalcon\Mvc\Model\Resultset

Hi,

I had a array data ,like

$data=[
    [
        'a'=>1,
        'b'=>1
    ],
    [
        'a'=>2,
        'b'=>3
    ],
];

and a model class,like:

class theModel extends PhalconModel{
    public $a;
    public $b;
} 

how to convert Phalcon\Mvc\Model\Resultset like phalcon model::find()?



32.2k

Try this

$collection = [];

foreach($data as $item){
    $model = new theModel()
    $model->assign($item);
    $collection[] = $model;
}

or maybe if you have a result from a PDO query

$resulset = Phalcon\Mvc\Model\Resultset\Simple(null, new theModel(), $results)

I didn't test these examples! Good luck!

I'm not sure if I get right, but you have model::find()->toArray() if you want an array

https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Model_Resultset.html

edited Jan '16

Using @noobiwan answer...

I had to implement this kind of model, related from another query without a specific table.

Solution:

Create a table without extending \Phalcon\Mvc\Model

After the raw query

    $connection = DI::getDefault()->get('db');
    $result_set = $connection->query($query);
    $result_set->setFetchMode(Db::FETCH_ASSOC);
    $result_set = $result_set->fetchAll($result_set);

Do a foreach on resultset then anither foreach for the propeties, assigning inside yout new model with PUBLIC properties.

    $collection = [];
    foreach ($inventoryItems as $item) {
        $model = new Model();
        foreach ($item as $k => $v) {
        $model->$k = $v;
    }
    $collection[] = $model;

That's the best sollution i could find, but you loose Resultset benefits.