我对yii2的RESTfull服务有疑问。
在cal视图中的(GET resource/{id}
)我想返回自定义值,该值取当前页面的编号,例如host/resource?page=x
(如果已设置),并且它加一(x + 1) )直到该数字等于X-Pagination-Total-Count标题的值。
所以响应将是这样的:
[
{
"id": 1,
"username": "test",
"email": "tset@email.it",
"status": 10,
"created_at": "2015-03-15 10:40:34"
}
{
"id": 2,
"username": "test1",
"email": "tset1@email.it",
"status": 10,
"created_at": "2014-05-12 12:50:26"
}
.
.
.
"custom_val" = x+1
]
有可能这样做吗?如何设置此值的返回值? 提前感谢所有的帮助。
修改:添加控制器代码
class UserController extends \yii\rest\ActiveController
{
// Model 'User'
public $modelClass = 'api\modules\v1\models\User';
/**
* Behaviors
*
* @return mixed
*/
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['contentNegotiator']['formats']['application/json'] = \yii\web\Response::FORMAT_JSON;
$behaviors['authenticator'] = [
'class' => \yii\filters\auth\HttpBasicAuth::className(),
];
return $behaviors;
}
/**
* Actions
*
* @return mixed
*/
public function actions()
{
$actions = parent::actions();
unset($actions['delete'], $actions['create'], $actions['update']);
$actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
return $actions;
}
/**
* Data Provider
*
* @return yii\data\ActiveDataProvider
*/
public function prepareDataProvider()
{
$data = User::find();
$provider = new \yii\data\ActiveDataProvider([
'query' => $data
]);
return $provider;
}
}
答案 0 :(得分:3)
试试这个:
public function afterAction($action, $result){
$result = parent::afterAction($action, $result);
if($action->id == 'index') //check controller action ID
$result['custom_val'] = 111;
return $result;
}