Yii2 REST create with fields()

末鹿安然 提交于 2020-01-16 05:12:27

问题


Let's say that I had the following API set up:

Controller:

<?php
namespace app\modules\v1\controllers;

use yii;

class ResourceController extends \yii\rest\ActiveController
{
    public $modelClass = 'app\modules\v1\models\Resource';
}

Model:

use yii;

class Resource extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return 'ResourceTable';
    }

    public function fields()
    {
        return [
            'id' => 'ResourceID',
            'title' => 'ResourceTitle',
        ];
    }
}

where my table only has the two columns, ResourceID and Title.

When I try a GET request on the API, it works fine and returns the list of resources (or single resource in the case of resource/{id}) with the aliased field names. But when I try to POST to create a resource, I want to use the aliased field names (e.g. title instead of ResourceTitle). The problem is that the default CreateAction supplied by Yii does $model->load(), which looks for the field names in the table. If I use the aliased names then it returns an error. If I use the table field names, it works fine.

So my question is, is there a way to expose resource attributes to the end user where the field names (using the fields() function) are the same for reading and creating? If possible, I'd like to avoid writing my own CreateAction.


回答1:


You can create getters/setters for alias.

public function getTitle(){ return $this->ResourceTitle; }
public function setTitle($val){ $this->ResourceTitle = $val ; }



回答2:


It's necessary to add rules for new virtual properties, if you want to $model-load() save parameters to them

class OrganizationBranch extends BaseOrganization{

public function rules()
    {
        return array_replace_recursive(parent::rules(),
        [
            [['organizationId', 'cityId'], 'safe'],
        ]);
    }

    public function fields() {
        return ['id', 
                'cityId' => 'city_id',
                'organizationId' => 'organization_id', 
                'address', 
                'phoneNumbers' => 'phone_numbers', 
                'schedule', 
                'latitude',         
                'longitude',
        ];
    }

    public function extraFields() {
        return ['branchType', 'city'];
    }

    public function getOrganizationId() {
        return $this->organization_id;
    }

    public function setOrganizationId($val) {
        $this->organization_id = $val;
    }

    public function getCityId() {
        return $this->city_id;
    }

    public function setCityId($val) {
        $this->city_id = $val;
    }

}


来源:https://stackoverflow.com/questions/31663403/yii2-rest-create-with-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!