0

How to return data in descending order in YII2 ActiveController? Please help me. The JSON response returned from activecontroller must be in descending order by news_id.

 <?php
    namespace app\api\modules\v1\controllers;
    use yii\web\Response;
    use yii\rest\ActiveController;

    class NewsController extends ActiveController {
      // We are using the regular web app modules:
      public $modelClass = 'app\models\News';
    }

This the news model

 <?php

    namespace app\models;

    use Yii;
    class News extends \yii\db\ActiveRecord
    {

        public static function tableName()
        {
            return 'news';
        }


        public function rules()
        {
            return [
                [['news_title', 'news_description', 'news_link'], 'required'],
                [['news_description', 'news_link'], 'string'],
                [['news_time'], 'safe'],
                [['news_title'], 'string', 'max' => 255],
            ];
        }


        public function attributeLabels()
        {
            return [
                'news_id' => 'News ID',
                'news_title' => 'News Title',
                'news_description' => 'News Description',
                'news_link' => 'News Link',
                'news_time' => 'News Time',
            ];
        }
    }
Rabindra Acharya
  • 1,868
  • 2
  • 18
  • 32

2 Answers2

1

Try send order with http query In your case it will be: api/web/v1/news?sort=-news_id

vityapro
  • 178
  • 1
  • 13
  • Can you gave next method to return data in descending order? – Rabindra Acharya Sep 05 '17 at 06:42
  • If you set `-` before attribute name (`-news_id`) it order in descending and if you path with out `-` simbol (`news_id`) it order in ascending order – vityapro Sep 05 '17 at 07:00
  • But i didn't found that the API which include (-) in my Android Development Process for API. So is there any way to call this api/web/v1/news so that it return descending order. – Rabindra Acharya Sep 05 '17 at 07:04
  • As far i understanded you problem, because my english not good enough, to solve it you can just set [sort order](http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#order-by) in model witch you use for selecting news just add to select query `$query->orderBy(['news_id' => SORT_DESC]);` of course if you use `QueryBuilder` or `ActiveRecords` – vityapro Sep 05 '17 at 10:23
0

Try this:

<?php $data = News::find()->orderBy('news_id DESC')->all()  ?>
Pratik Karmakar
  • 247
  • 1
  • 8