You are viewing a read-only archive of the Blogs.Harvard network. Learn more.

Yii default ORDER BY

I ran into an issue with a minor difference between Oracle and MySQL. Apparently MySQL is better about returning rows in the order they were inserted than Oracle. Now if you want to let me know it’s wrong to assume results are returned in any specific order, I know! Neither gives any guarantee on the order of results without an ORDER BY, but Oracle is semi-random.

It took me a little while to find the right way to add default items to queries. Yii uses CActiveRecords for model queries. I already had an overridden CActiveRecord class from Yii handling “getLastInsertId” with Oracle. So I knew I would be able to use that somehow.

I finally discovered scopes. It allows me to define a scope:

public function scopes()
{
    return array(
        'sort_order'=>array(
            'order'=>'SORT_ORDER ASC',
        ),
        'id_order'=>array(
            'order'=>'ID ASC',
        ),
    );
}

and then use it as such:

MyModel::model()->id_order()->FindAllByAttributes(array('SOMECOLUMN'=>1))

But still I didn’t find anything on default scopes. On a whim I did a grep -i “defaultscope” on the code and discovered it exists in the Yii framework. So I was able to piece together the following:

public function defaultScope()
{
    return array(
 	'order'=>'ID ASC'
    );
}

and bam. Add that to my QActiveRecord, and it’s golden.

Leave a comment