在yii2中使用函数field()的正确方法

时间:2015-08-06 11:36:04

标签: api rest yii2

我正在为我的项目编写REST API。

我的模型中的

field()函数:

public function fields()
{
    $fields = parent::fields();

    // remove fields that contain sensitive information
    unset($fields['media'], $fields['content']);

    return $fields;
}

我有2个动作:

/api/resources - 获取所有资源列表

这个api回归:

"items":
[
    {
        "ID": 1,
        "category_id": 1,
        "title": "tset",
        "image": "1437537044.png",
        "ins_date": "2015-07-22 00:00:00",
        "count": 20
    },
    {
        "ID": 2,
        "category_id": 1,
        "title": "tset",
        "image": "1437537176.png",
        "ins_date": "2015-07-22 00:00:00",
        "count": 0
    },

/api/resources/view?id=1 - 获取有关资源ID = 1

的所有信息
{
    "ID": 1,
    "category_id": 1,
    "title": "tset",
    "image": "1437537044.png",
    "ins_date": "2015-07-22 00:00:00",
    "count": 21
}

我获得了所有资源,但是当我像这样调用actionView($id)时,我希望得到所有字段:

{
    "ID": 1,
    "category_id": 1,
    "title": "tset",              // I want to get response with this 
    "content": "test",            //and this fields
    "media": "test",
    "image": "1437537044.png",
    "ins_date": "2015-07-22 00:00:00",
    "count": 22
}

HOw可以解决这个问题吗?帮帮我?

1 个答案:

答案 0 :(得分:1)

  1. 使用具有不同字段的模型的子类()

  2. use Yii::$app->controller->action->uniqueId

    public function fields()
    {
        if(Yii::$app->controller->action->uniqueId == 'controller/action'){
            return ['field_1','field_2','field_3','field_4'];
        }else{
            return ['field_1','field_3'];
        }
    }
    
  3. Extended yii\rest\Serializer change init() and getRequestedFields()