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

Alter Default Model::find() behavior?

Is there a way to alter the default Model::find() query? With something such as making it order by a certain field by default or do we have to use afterFetch() and sort it through PHP commands?

I guess I should have posted more detail.....

The reason why is because I have for instance a countries table and I know that anytime I need the countries I'm going to sort it by the weight column and then the name column on every single drop down I do for countries.

I could do Countries::find(array(“order” => “weight DESC, name ASC”)), but doing that on everything...... :(



98.9k

You can intercept the find action and change its behavior:

class Countries extends Phalcon\Mvc\Model
{
    public static function find($params=null)
    {
        if (is_array($params)) {
            if (!isset($params['order'])) {
                $params['order'] = 'weight DESC, name ASC';
            }
        }
        return parent::find($params);
    }   
}


18.6k
Accepted
answer

Perfect! Just what I needed.