我正在尝试使用 yii2 的 REST api 获取 json 格式的所有项目的列表。基本上,它返回一个包含 20 个项目的列表,没有排序。但我需要某种类型的所有元素。如果我必须向他们展示,我也许可以以这种方式重新定义 Controller 的 Action 索引:
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,
]);
}
但是我该怎么做才能以相同的方式更改其余查询的响应?
最佳答案
您可以为索引操作重新定义 prepareDataProvider
。
public function actions()
{
$actions = parent::actions();
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
这将从您的 Controller 调用 prepareDataProvider
方法而不是内置方法。
例如:
public function prepareDataProvider()
{
$searchModel = new SiteDictionarySearch();
$dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
return $dataProvider;
}
并且您应该为您的模型制作搜索模型以满足此类需求。要更好地返回所有项目,请使用 ArrayDataProvider
和 find()->asArray()
返回应该是这样的:
return new ArrayDataProvider([
'allModels' => $rows,
'pagination' => [
'pageSize' => count($rows),
],
]);
关于php - yii2 REST API 调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33955965/