更改一个属性值 Yii2 REST API
Change one attribute value Yii2 REST API
我使用 ActiveController
在 Yii2 中创建了一个 REST API。默认实现actionIndex
return所有机型。
我想要做的是在发送响应之前更改一个属性的值。
例如,我上传的图像仅将其名称存储在数据库中。
在发送响应之前,我想嵌入带有图像名称的基础 URL。
我需要覆盖整个索引方法还是可以在 action
方法中操作单个属性?
我认为最简单的方法是覆盖模型中的 fields()
方法。假设您为名为 YourFile
的模型配置了 ActiveController。如果将以下函数添加到 YourFile
模型,则可以为响应中的每个模型添加完整的 url:
public function fields() {
return [
'id',
'name' => function() {
return Url::base(true) . $this->name;
}
]
}
如果你这样添加它,这确实意味着在你的模型上调用 toArray()
的每个代码都会得到这个结果。如果您只希望它发生在 ActiveController
上,您可能需要扩展 YourFile
模型并仅在其中包含 fields()
方法,因此您可以使用 ActiveController
配置加长版。
我们还可以更改某些字段的显示名称:
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {
/** * API safe fields */
public function fields() {
return [
'id',
'email_address' => 'email',
'first_name',
'last_name',
'full_name' => function($model) {
return $model->getFullName();
},
'updated_at',
'created_at'
];
}
}
在此处查看完整教程:
http://p2code.com/post/configuring-activecontroller-display-fields-yii-2-21
我使用 ActiveController
在 Yii2 中创建了一个 REST API。默认实现actionIndex
return所有机型。
我想要做的是在发送响应之前更改一个属性的值。
例如,我上传的图像仅将其名称存储在数据库中。
在发送响应之前,我想嵌入带有图像名称的基础 URL。
我需要覆盖整个索引方法还是可以在 action
方法中操作单个属性?
我认为最简单的方法是覆盖模型中的 fields()
方法。假设您为名为 YourFile
的模型配置了 ActiveController。如果将以下函数添加到 YourFile
模型,则可以为响应中的每个模型添加完整的 url:
public function fields() {
return [
'id',
'name' => function() {
return Url::base(true) . $this->name;
}
]
}
如果你这样添加它,这确实意味着在你的模型上调用 toArray()
的每个代码都会得到这个结果。如果您只希望它发生在 ActiveController
上,您可能需要扩展 YourFile
模型并仅在其中包含 fields()
方法,因此您可以使用 ActiveController
配置加长版。
我们还可以更改某些字段的显示名称:
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {
/** * API safe fields */
public function fields() {
return [
'id',
'email_address' => 'email',
'first_name',
'last_name',
'full_name' => function($model) {
return $model->getFullName();
},
'updated_at',
'created_at'
];
}
}
在此处查看完整教程: http://p2code.com/post/configuring-activecontroller-display-fields-yii-2-21