Yii2:如何在Find()的orderby()中添加两个字段

时间:2016-06-15 08:53:45

标签: php yii2

如何在find()方法中添加多个字段进行排序?

我试过如下

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

但它在查询时抛出错误。 由yii2生成的Orderby Query是:ORDER BY 0, 1

3 个答案:

答案 0 :(得分:28)

根据documentation

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

答案 1 :(得分:1)

以下代码中有语法错误:

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

正确的方法是:

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

答案 2 :(得分:-2)

class NewsController extends Controller
{

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