通过重写field()和extraFields()方法,可以定义可以将哪些数据放入响应中。这两种方法的区别在于,前者定义了默认字段集,应将其包含在响应中,而后者则定义其他字段,如果最终用户通过expand query参数请求它们,则可以将其包含在响应中。
步骤1-以这种方式修改MyUser模型。
<?php namespace app\models; use app\components\UppercaseBehavior; use Yii; /** * This is the model class for table "user". *@property integer $id * @property string $name * @property string $email */ class MyUser extends \yii\db\ActiveRecord { public function fields() { return [ 'id', 'name', //PHP callback 'datetime' => function($model) { return date("d:m:Y H:i:s"); } ]; } /** * @inheritdoc */ public static function tableName() { return 'user'; } /** * @inheritdoc */ public function rules() { return [ [['name', 'email'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Name', 'email' => 'Email', ]; } } ?>
除了默认字段:id和name外,我们还添加了一个自定义字段– datetime。
步骤2-在Postman中,运行URL http:// localhost:8080 / users。
步骤3-现在,以这种方式修改MyUser模型。
<?php namespace app\models; use app\components\UppercaseBehavior; use Yii; /** * This is the model class for table "user". * * @property integer $id * @property string $name * @property string $email */ class MyUser extends \yii\db\ActiveRecord { public function fields() { return [ 'id', 'name', ]; } public function extraFields() { return ['email']; } /** * @inheritdoc */ public static function tableName() { return 'user'; } /** * @inheritdoc */ public function rules() { return [ [['name', 'email'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Name', 'email' => 'Email', ]; } } ?>
请注意,电子邮件字段是由extraFields()方法返回的。
步骤4-要使用此字段获取数据,请运行http:// localhost:8080 / users?expand = email。
该警予\其他\ ActiveController类提供了以下措施-
以上所有动作均在actions方法中声明。
要禁用“删除”和“创建”操作,请以这种方式修改UserController-
<?php namespace app\controllers; use yii\rest\ActiveController; class UserController extends ActiveController { public $modelClass = 'app\models\MyUser'; public function actions() { $actions = parent::actions(); // disable the "delete" and "create" actions unset($actions['delete'], $actions['create']); return $actions; } } ?>
获取RESTful API请求时,如果请求中有错误或服务器上发生意外情况,则可以简单地引发异常。如果可以确定错误原因,则应引发异常以及正确的HTTP状态代码。Yii REST使用以下状态-