Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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...... :(



82.2k

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);
    }   
}


12.7k
Accepted
answer

Perfect! Just what I needed.