2015-11-27 83 views
1

我正在嘗試使用yii2的REST api獲取json格式中所有項目的列表。基本上,它返回一個沒有排序的20個項目的列表。但我需要某種東西。如果我不得不告訴他們,我可能會重新定義控制器的動作指數這樣的方式:yii2 rest api tuning

public function actionIndex() 
{ 
    $modelClass = $this->modelClass; 
    $dictionaries = $modelClass::find()->select([ 
      '{{site_search_dictionary}}.*', // select all customer fields 
      'COUNT(*) AS dd' // calculate orders count 
     ]) 
     ->joinWith('queries') // ensure table junction 
     ->groupBy('dictionary_id') // group the result to ensure aggregation function works 
      ->orderBy('dictionary')->all(); 

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

但我能做些什麼來改變同樣的方式迴應休息查詢?

回答

0

我想你可以用它舔這個

public function actionIndex() 
{ 
$modelClass = $this->modelClass; 
$dictionaries = $modelClass::find()->select([ 
     '{{site_search_dictionary}}.*', // select all customer fields 
     'COUNT(*) AS dd' // calculate orders count 
    ]) 
    ->joinWith('queries') // ensure table junction 
    ->groupBy('dictionary_id') // group the result to ensure aggregation function works 
     ->orderBy(['dictionary_id'=>SORT_ASC])->all(); 

return $this->render('index', [ 
    'dictionaries' => $dictionaries, 
]); 
} 
+0

不,它沒有任何結果。我認爲可能重新定義prepareDataProvider可以提供幫助,但我不知道在這種情況下我應該返回什麼。 –

+0

重新定義prepareDataprovider是什麼意思?數據提供者在哪裏? –

1

你可以重新定義prepareDataProvider索引操作。

public function actions() 
     { 
      $actions = parent::actions(); 
      $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider']; 

      return $actions; 
     } 

這將從您的控制器調用prepareDataProvider方法而不是內置方法。

例如:

public function prepareDataProvider() 
     { 
      $searchModel = new SiteDictionarySearch(); 
      $dataProvider = $searchModel->search(\Yii::$app->request->queryParams); 
      return $dataProvider; 
     } 

你應該讓你的模型,這樣的需求的搜索模式。要返回所有項目更好地利用ArrayDataProviderfind()->asArray()

這裏是回報應該什麼樣子:

return new ArrayDataProvider([ 
       'allModels' => $rows, 
       'pagination' => [ 
        'pageSize' => count($rows), 
       ], 
      ]); 
+0

是的,但是爲什麼我需要使用ArrayDataProvider,如果我想將結果格式化爲json? –

+0

您可以改爲返回activeDataProvider,但會遇到分頁限制問題。在休息時查看IndexAction的源代碼。 – ineersa

+0

好吧,好,現在它工作正常,但似乎find() - > asArray()在這裏沒有必要 - 導致find-> select ...的結果已經是一個數組。 –