【问题标题】:How to return data in descending order in YII2 ActiveController?如何在 YII2 ActiveController 中按降序返回数据?
【发布时间】:2017-08-29 11:14:49
【问题描述】:

如何在YII2 ActiveController中按降序返回数据?请帮我。从activecontroller返回的JSON响应必须在由news_id降序排列。 P>

 <?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';
    }

这是新闻模型

 <?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',
            ];
        }
    }

【问题讨论】:

  • 添加您的问题查询和相关模型。 SPAN>
  • 我添加了模型类。你可以把一些想法返回数据NI从大到小的顺序? SPAN>

标签: yii2 yii2-basic-app yii2-api


【解决方案1】:

尝试使用 http query 发送订单 在您的情况下,它将是: api/web/v1/news?sort=-news_id

【讨论】:

  • 你能给出下一个按降序返回数据的方法吗?
  • 如果你在属性名(-news_id)之前设置-,它会按降序排列,如果你的路径没有- simbol(news_id)它会按升序排列
  • 但是我没有发现包含 (-) 的 API 包含在我的 Android API 开发过程中。那么有什么方法可以调用这个 api/web/v1/news 以便它返回降序。
  • 据我了解您的问题,因为我的英语不够好,要解决它,您可以在用于选择新闻的模型中设置sort order,当然只需添加到选择查询$query-&gt;orderBy(['news_id' =&gt; SORT_DESC]);如果您使用QueryBuilderActiveRecords
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 2017-03-03
    • 2017-10-12
    相关资源
    最近更新 更多