1

我有一个关于 yii2 的 RESTfull 服务的问题。

在 cal 视图(GET resource/{id})中,我想返回以当前页面编号为例的自定义值host/resource?page=x(如果已设置),并且它总和为 1(x+1),直到该数字等于 X-Pagination 的值- 总计数标题。

所以响应将是这样的:

[
      {
        "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;
    }

}
4

1 回答 1

4

试试这个:

public function afterAction($action, $result){

    $result = parent::afterAction($action, $result);

    if($action->id == 'index') //check controller action ID
        $result['custom_val'] = 111;

    return $result;
}
于 2016-06-15T10:53:30.070 回答