19
votes

How to add more than one field to sort in find() method?

I have tried as below

$model::find()->orderBy([['id_date' => SORT_DESC],['item_no'=>SORT_ASC]);

But it is throwing error with query. Orderby Query produced by yii2 is: ORDER BY 0, 1

3
This question might help you.Jurik
@Jurik I'm using find() function. not CActiveDataProvider. Also, I'm yii2.Kumar V

3 Answers

48
votes

According to the documentation:

$model::find()->orderBy([
  'id_date' => SORT_DESC,
  'item_no'=>SORT_ASC
]);
2
votes

You have a syntax error in the following code:

$model::find()->orderBy([['id_date' => SORT_DESC], ['item_no' => SORT_ASC]);

The correct way of doing this is:

$model::find()->orderBy(['id_date' => SORT_DESC, 'item_no' => SORT_ASC]);
-1
votes
class NewsController extends Controller
{

    public function actionIndex ()
    {   $news = \common\models\News::find()->orderBy(['date' => SORT_DESC])->all();
        return $this->render("index",[
            'news' => $news
        ]);
    }
}