Search code examples
phpsql-serversortingyiimodels

Yii sorting in model via certain values


I have a CGridView with a table tblDetails . I need to sort the table's data not by asc or desc, but by values. the column to sort is status

column values:
1) New
2) Pending
3) Awaiting approval
4) Open
5) Approved/Closed

So I need the data sorted as in this way :

New data
open data
pending data
and so forth.

So not by asc desc. And I cannot change the table to accommodate that because that would be cheating.

I would preferably like to do this in the model in search function but if there is a better way please mention it.


Solution

  • to do such thing you need SQL statement like this.

    SELECT status FROM table_name 
        ORDER BY CASE name 
            WHEN 'New data' THEN 1 
            WHEN 'open data' THEN 2 
            WHEN 'pending data' THEN 3 
        END;
    

    in Yii model:

    $criteria = new CdbCriteria();
    $criteria->order ="CASE Column_name
        WHEN 'New data' THEN 1 
        WHEN 'open data' THEN 2 
        WHEN 'pending data' THEN 3 
    END";
    return new CActiveDataProvider ($this, array(
        'criteria'=>$criteria, //ordered criteria sent to CGridView
    ));
    

    PS. tested under mysql - it works :)