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

ORM arguments: fields/values as arrays

Hey there,

I've been using Phalcon for a while now, mostly for personal projects, but in my main job I use CakePHP.

One thing I miss from Cake when using Phalcon is the ability of Cake's ORM to translate arrays to fields/values of a SQL statement, for example:

    public function updateProducts($entity){
        TableRegistry::get('InventoryProducts')
            ->query()
            ->update()
            ->set([
                'inventory_id' => $entity->id
            ])
            ->where([
                'uid' => $entity->uid,
                'inventory_id' => 0
            ])
            ->execute();
    }

In Phalcon, the user has to bind the variables to their placehoders in the SQL statement (In order to prevent SQL injection), which is later processed by PHQL; this effort could be avoided by using this syntax, among other advantages, like manipulating the query later more easily.

I think one could use a hack to explode(",", $theArguments) But it would be a better solution to have this feature natively in the ORM.

If it has been already implemented or is planned for future realeases, please let me know; otherwise I would like to know how much effort it would take to do it. I would gladly contribute to the development of this feature.

You can already do something like:

InventoryProducts::find([
    'uid = :uid: AND inventory_id = :inventoryId:',
    'bind' => [
        'uid' => $entity->uid,
        'inventoryId' => 0
    ]
])->update(['inventory_id' => $entity->id]);

It will be same if you will use UPDATE query in PHQL, what phalcon actually does anyway is to select all rows and then update it using ORM.

Thanks for your answer, is there a way to do the same with the query conditions? I want to be able to manipulate the query conditions as key/values from an array (For scalability purposes).

In other words, is this possible?

InventoryProducts::find([
    [
      'uid' => $uid,
      'inventory_id' => $inventoryId,
    ],
    'bind' => [
        'uid' => $entity->uid,
        'inventoryId' => 0
    ]
])->update(['inventory_id' => $entity->id]);

would be awesome autobind by array index

Currently there is no such option, but you can always create such NFR on github. I think this could be implemented without any breaking things.