yii 提供了两种数据提供器 ActiveDataProvider和SqlDataProvider
使用方法也是非常简单 具体可查询官方文档
$model = new ActiveDataProvider(['query'=>$query]);
$result = new SqlDataProvider(['sql'=>$sql ]);
效果如下
如果当前数据模式满足不了我们的业务需求怎么增加返回字段
- 接口拆分写两个接口
- 更改Yii代码进行多字段返回(如我们统一返回info字段)
首先建立base层(继承)
// ActiveDataProvider.php
class ActiveDataProvider extends \yii\data\ActiveDataProvider
{
public $info;
}
//SqlDataProvider.php
class SqlDataProvider extends \yii\data\SqlDataProvider
{
public $info;
}
//MySerializer.php 改文件可在base控制器中使用
//public $serializer = [
// 'class' => '\base\MySerializer',
// 'collectionEnvelope' => 'data',
// ];
//也可在需要返回改格式的控制器中使用
<?php
namespace backend\modules\v2\base;
class MySerializer extends \yii\rest\Serializer
{
/**
* 应app端要求,重写serializeDataProvider方法,加上code=1
* @param \yii\data\DataProviderInterface $dataProvider
* @return array|null
*/
protected function serializeDataProvider($dataProvider)
{
if ($this->preserveKeys) {
$models = $dataProvider->getModels();
} else {
$models = array_values($dataProvider->getModels());
}
$models = $this->serializeModels($models);
if (($pagination = $dataProvider->getPagination()) !== false) {
$this->addPaginationHeaders($pagination);
}
if ($this->request->getIsHead()) {
return null;
} elseif ($this->collectionEnvelope === null) {
return $models;
}
$result = [
'code' => 1,
$this->collectionEnvelope => $models,
];
if(isset($dataProvider->info)) $result['info'] = $dataProvider->info;//自定义增加返回条件
if ($pagination !== false) {
return array_merge($result, $this->serializePagination($pagination));
}
return $result;
}
}
然后效果数据如下