Yii2 REST create with fields()

2019-08-06 09:09发布

问题:

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;
    }

}


标签: api rest yii2