2015-07-28 14:57:49 4152次浏览 4条回答 2 悬赏 50 金钱

看了下SQL默认没有排序,怎么做到默认id desc?

public function actionIndex()
{
    $sort = new Sort([
        'attributes' => [
            'id' => [
                'desc' => ['id'=>SORT_DESC],
                'asc' => ['id'=>SORT_ASC],
                'default' => SORT_DESC,
                'label' =>'#Id',
            ],
            'hot' => [
                'asc' => ['hot'=>SORT_ASC],
                'desc' => ['hot'=>SORT_DESC],
                'label' =>'#即时热度',
            ],
            'add_hot' => [
                'asc' => ['add_hot'=>SORT_ASC],
                'desc' => ['add_hot'=>SORT_DESC],
                'label' =>'#增减热度',
            ],
        ],
    ]);

    $query = Dynamic::find();

    $pages = new Pagination([
        'defaultPageSize' => 10,
        'totalCount' => $query->count(),
    ]);

    $models = $query
        ->where(['status' => 0])
        ->orderBy($sort->orders)
        ->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

    return $this->render('index',[
        'models' => $models,
        'sort' => $sort,
        'pages' => $pages,
    ]);
}

最佳答案

  • 发布于 2015-07-28 17:33 举报
    $sort = new Sort([
            'attributes' => [
                'id' => [
                    'desc' => ['id'=>SORT_DESC],
                    'asc' => ['id'=>SORT_ASC],
                    'default' => SORT_DESC,
                    'label' =>'#Id',
                ],
                'hot' => [
                    'asc' => ['hot'=>SORT_ASC],
                    'desc' => ['hot'=>SORT_DESC],
                    'label' =>'#即时热度',
                ],
                'add_hot' => [
                    'asc' => ['add_hot'=>SORT_ASC],
                    'desc' => ['add_hot'=>SORT_DESC],
                    'label' =>'#增减热度',
                ],
            ],
            'defaultOrder' => ['id' => SORT_DESC], // 看这里看这里看这里,重要的话说三遍
        ]);
    
    , , , , 觉得很赞
您需要登录后才可以回答。登录 | 立即注册
trylife
总监

trylife Beijing

注册时间:2015-03-26
最后登录:2020-12-07
在线时长:51小时55分
  • 粉丝39
  • 金钱1626
  • 威望40
  • 积分2536

热门问题