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

[Tips] How to use raw model query

Hi guys.

After many attempts to find the most correct and easy solution to this problem came to the conclusion that it is better to do so. (Correct me if there is a simple and intuitive method)

Creating a model:

<?php

    /**
    *   Raw query model
    *
    */

    class SQL extends Phalcon\Mvc\Model
    {
        public function q($query) {

            return new \Phalcon\Mvc\Model\Resultset\Simple(
                null, 
                $this, 
                $this->getReadConnection()->query($query)
            );

        }

    }

Use:

public function someAction() {

    $users = (new SQL)->q('select * from users');

    foreach($users as $user) {
        echo $user->firstname . '<br>';
    }

}

Sorry for my english dialect :) again

Better to do as static method. Also this query oucan just do in ORM. Fi this don't need to be hydrated you can just use $di->get("db") https://docs.phalcon.io/pl/latest/api/Phalcon_Db_Adapter_Pdo.html