Yii2模型获取包含下划线的字段的方法
Yii2 model get method for field containing underscore
模型名称:listing
;
字段名称:contact_name
.
涉及用户输入,因此我想使用 getContactName
的某些变体始终如一地格式化输出,即任何对 $model->contact_name
returns 格式化输出的调用。是的,例如,我可以使用 getContactName
和 $model->contactName
,但我还没有找到可以与默认 $model->contact_name
.[=18= 一起使用的 getcontact_name
的任何变体]
我知道我可以配置 Gii 来创建一些额外的功能,以及其他各种变通方法,但我很感兴趣,在一个体面的 Google 之后,是否有一个简单的解决方案。
您可以覆盖所需模型的 afterFind()
方法并覆盖默认值,或将默认值格式化为您所需的格式。
您可以通过将以下内容添加到您的模型中来覆盖该方法 Listing
。
假设我们需要格式化在 table 中保存为 rich-harding
的默认联系人姓名,我们将其格式化为 Rich Harding
public function afterFind() {
parent::afterFind();
$names=explode("-",$this->contact_name);
$this->contact_name=implode(" ", array_map('ucfirst',$names));
}
如果您已经拥有名称为 contact_name
的属性(或常规对象 属性),getContact_name()
将不起作用。来自数据库的属性优先于 getters/setters - 您可以在 __get()
source code 中看到这一点。显然 __get()
如果你有真正的 属性 这个名字,将永远不会被调用。因此将按以下顺序搜索值:
- Object properties.
- 来自数据库的属性。
- Getters/setters(包括关系)。
您应该使用不同的名称 (contactName
),或者使用 afterFind
事件进行格式化或覆盖 __get()
以更改数据源的顺序(这可能很棘手)。您可能还对 this PR.
感兴趣
模型名称:listing
;
字段名称:contact_name
.
涉及用户输入,因此我想使用 getContactName
的某些变体始终如一地格式化输出,即任何对 $model->contact_name
returns 格式化输出的调用。是的,例如,我可以使用 getContactName
和 $model->contactName
,但我还没有找到可以与默认 $model->contact_name
.[=18= 一起使用的 getcontact_name
的任何变体]
我知道我可以配置 Gii 来创建一些额外的功能,以及其他各种变通方法,但我很感兴趣,在一个体面的 Google 之后,是否有一个简单的解决方案。
您可以覆盖所需模型的 afterFind()
方法并覆盖默认值,或将默认值格式化为您所需的格式。
您可以通过将以下内容添加到您的模型中来覆盖该方法 Listing
。
假设我们需要格式化在 table 中保存为 rich-harding
的默认联系人姓名,我们将其格式化为 Rich Harding
public function afterFind() {
parent::afterFind();
$names=explode("-",$this->contact_name);
$this->contact_name=implode(" ", array_map('ucfirst',$names));
}
contact_name
的属性(或常规对象 属性),getContact_name()
将不起作用。来自数据库的属性优先于 getters/setters - 您可以在 __get()
source code 中看到这一点。显然 __get()
如果你有真正的 属性 这个名字,将永远不会被调用。因此将按以下顺序搜索值:
- Object properties.
- 来自数据库的属性。
- Getters/setters(包括关系)。
您应该使用不同的名称 (contactName
),或者使用 afterFind
事件进行格式化或覆盖 __get()
以更改数据源的顺序(这可能很棘手)。您可能还对 this PR.