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',
            ];
        }
    }
2
  • 2
    add your query and related model in question. Commented Aug 29, 2017 at 11:57
  • I have added model class. Can you gave some idea to return the data ni descending order? Commented Sep 5, 2017 at 6:45

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Can you gave next method to return data in descending order?
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
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.
As far i understanded you problem, because my english not good enough, to solve it you can just set sort order 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
0

Try this:

<?php $data = News::find()->orderBy('news_id DESC')->all()  ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.