开发者

Rearranging active record elements in Yii

I am using a CDbCriteria with its own conditions, with & order clauses. However, the order i want to give to the elements in the array is way too complex to s开发者_StackOverflow中文版pecify in the order clause.

The solution i have in mind consists of obtaining the active records with the defined criteria like this

$theModelsINeed = MyModel::model()->findAll($criteria); 

and then rearrange the order from my php code. How can i do this? I mean, i know how to iterate through its elements, but i don´t know if it is possible to actually change them.

I have been looking into this link about populating active records, but it seems quite complicated and maybe someone could have some better advice.

Thanks


There is nothing special about Yii's active records. The find family of methods will return an array of objects, and you can sort this array like any other array in PHP.

If you have complex sort criteria, this means that probably the best tool for this is usort. Since you will be dealing with objects, your user-defined comparison functions will look something like this:

function compare($x, $y)
{
    // First sort criterion: $obj->Name
    if ($x->Name != $y->Name) {
        return $x->Name < $y->Name ? -1 : 1; // this is an ascending sort
    }

    // Second sort criterion: $obj->Age
    if ($x->Age != $y->Age) {
        return $x->Age < $y->Age ? 1 : -1; // this is a descending sort
    }

    // Add more criteria here

    return 0; // if we get this far, the items are equal
}


If you do want to get an array as a result, you can use this method for fetching data that supports dbCriteria:

$model = MyModel::model()->myScope();
$model->dbCriteria->condition .= " AND date BETWEEN :d1 AND :d2";
$model->dbCriteria->order = 'field1 ASC, field2 DESC';
$model->dbCriteria->params = array(':d1'=>$d1, ':d2'=>$d2);

$theModelsINeed = $model->getCommandBuilder()
    ->createFindCommand($model->tableSchema, $model->dbCriteria)
    ->queryAll();

The above example shows using a defined scope and modifying the condition with named parameters.

If you don't need Active Record, you could also look into Query Builder, but the above method has worked pretty well for me when I want to use AR but need an array for my result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜