Search code examples
phpyii

Yii - findAll with order by


How to findAll with specific column with order by desc ?

Code bellow worked and find all from the developer id

$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id);

Code bellow worked and ordered

$models = Games::model()->findAll(array('order'=>'status'));

When I mixed together then only worked for findAll developer_id='.$id doesn't order by

$id = Yii::app()->user->getState('id');
$models = Games::model()->findAll('developer_id='.$id,array('order'=>'status'));

Any suggestion to do that ? Thanks


Solution

  • In your model, add this function:

    public function scopes() {
        return array(
            'bystatus' => array('order' => 'status DESC'),
        );
    }
    

    Now you can do the query like this:

    $models = Games::model()->bystatus()->findAll('developer_id='.$id);
    

    =====

    Bonus: You can also add this function in your model:

    public function bydeveloper($devId) {
        $this->getDbCriteria()->mergeWith(array(
            'condition' => 'developer_id = '.$devId,
        ));
        return $this;
    }
    

    Now you can do the query like this:

    $models = Games::model()->bystatus()->bydeveloper($id)->findAll();