我是Yii 2的新用户,我的基本API工作正常,现在我正在尝试更改从数据库返回的字段名称,
所以我在我的模型中添加了attributeLabels()
并更改了字段的名称,但它没有反映出来。
任何人都能帮助我吗?下面是我的模型代码(这是用于API)。
public function attributeLabels()
{
return [
'ID' => 'ID',
'LOGIN' => 'Login',
'FIRST_NAME' => 'First Name',
'LAST_NAME' => 'Last Name',
'EMAIL_ADDRESS' => 'Email Address',
];
}
我是否必须在控制器中添加任何内容?我只有actionIndex
才能返回所有记录。以下是我的控制器中的代码
public function actionIndex()
{
$model = Phdlist::find()
->limit(100)
->all();
Yii::$app->response->format = Response::FORMAT_JSON;
return $model;
}
答案 0 :(得分:1)
属性标签用于显示目的,不会成为模型属性的关键。 在你的函数中你似乎需要返回一组模型(在JSON_FORMAT中)
在集合中,您检索单个对象属性的名称是基于keyname:
'ID'
'LOGIN'
'FIRST_NAME'
'LAST_NAME'
'EMAIL_ADDRESS'
答案 1 :(得分:0)
如果我理解正确,那么您应该使用yii\base\Model::fields()
来解决问题。
结帐http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#fields,特别是标题为覆盖fields()
的部分。
默认情况下,
yii\base\Model::fields()
会返回所有模型属性 字段,而yii\db\ActiveRecord::fields()
只返回 已从DB填充的属性。您可以覆盖
fields()
来添加,删除,重命名或重新定义字段。
以下是该页面的相关示例(特别是'email' => 'email_address'
) -
// explicitly list every field, best used when you want to make sure the changes
// in your DB table or model attributes do not cause your field changes (to keep API backward compatibility).
public function fields()
{
return [
// field name is the same as the attribute name
'id',
// field name is "email", the corresponding attribute name is "email_address"
'email' => 'email_address',
// field name is "name", its value is defined by a PHP callback
'name' => function ($model) {
return $model->first_name . ' ' . $model->last_name;
},
];
}
您需要将此添加到您的模型代码中。在您的情况下,它将是'login' => 'username'
。但请注意,属性名称不能包含空格。因此,据我所知,'first_name' => 'first name'
无法正常工作。