Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii - findAll with order by

Tags:

php

yii

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

like image 784
TheSmile Avatar asked Nov 17 '14 02:11

TheSmile


3 Answers

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();
like image 188
Samuel Liew Avatar answered Nov 05 '22 05:11

Samuel Liew


you can try this -

$id = Yii::app()->user->getState('id');

$model = Games::model()->findAll(array("condition" => "developer_id = '".$id."'","order" => "status"));

its should be work

like image 10
Milap Jethwa Avatar answered Nov 05 '22 04:11

Milap Jethwa


You can try use criteria:

$id = Yii::app()->user->getState('id');
$criteria=new CDbCriteria;
$criteria->compare('developer_id',$id);
$criteria->order='status DESC';

$models = Games::model()->findAll($criteria);
like image 1
wawancell Avatar answered Nov 05 '22 04:11

wawancell