Yii2 REST创建与fields() [英] Yii2 REST create with fields()

查看:195
本文介绍了Yii2 REST创建与fields()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我设置了以下API:

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

控制器:

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

use yii;

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

型号:

use yii;

class Resource extends \yii\db\ActiveRecord
{

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

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

我的表中只有两列ResourceIDTitle.

当我在API上尝试GET请求时,它可以正常工作并返回带有别名字段名称的资源列表(对于resource/{id},则返回单个资源).但是当我尝试POST创建资源时,我想使用别名字段名称(例如title而不是ResourceTitle).问题是Yii提供的默认CreateAction会执行$model->load(),它会在表中查找字段名称.如果我使用别名,则返回错误.如果我使用表字段名称,则可以正常工作.

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.

所以我的问题是,有没有一种方法可以将资源属性公开给最终用户,而这些字段名(使用fields()函数)在读取和创建时都是相同的?如果可能的话,我想避免编写自己的CreateAction.

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.

推荐答案

您可以为别名创建getter/setter.

You can create getters/setters for alias.

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

这篇关于Yii2 REST创建与fields()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆