Yii2模型获取包含下划线的字段的方法 [英] Yii2 model get method for field containing underscore

查看:281
本文介绍了Yii2模型获取包含下划线的字段的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号名称:listing; 字段名称:contact_name.

Model name: listing; Field name: contact_name.

涉及到用户输入,因此我想使用getContactName的某些变体来一致地格式化输出,即,对$model->contact_name的任何调用都将返回格式化的输出.是的,我可以使用例如getContactName$model->contactName,但是我没有找到任何可以与默认$model->contact_name配合使用的getcontact_name变体.

User input involved, so I want to format the output, consistently, with some variant of getContactName, i.e. any call to $model->contact_name returns the formatted output. Yes, I can use, for example, getContactName and $model->contactName, but I have not found any variant of getcontact_name that will work with the default $model->contact_name.

我知道我可以配置Gii来创建一些附加功能以及其他各种解决方法,但是我对一个像样的Google感兴趣,是否有一个简单的解决方案.

I'm aware that I could configure Gii to create some additional functions, and various other workarounds, but I'm interested, after a decent Google, in whether there is a straightforward solution.

推荐答案

getContact_name()将不起作用.来自数据库的属性优先于getter/setter-您可以在 __get()源代码.如果您拥有使用此名称的不动产,显然不会调用__get().因此,将按以下顺序搜索值:

getContact_name() will not work if you already have attribute (or regular object property) with contact_name as a name. Attributes from database have precedence over getters/setters - you can see this in __get() source code. And obviously __get() will never be called if you have real property with this name. So value will be searched in this order:

  1. 对象属性.
  2. 数据库中的属性.
  3. 字母/字母(包括关系).

您应该使用其他名称(contactName),或者使用afterFind事件进行格式化或覆盖__get()来更改数据源的顺序(这可能很棘手).您可能也会对此PR 感兴趣.

You should either use different name (contactName), or do formatting using afterFind event or override __get() to change order of data sources (this could be tricky). You may be also interested in this PR.

这篇关于Yii2模型获取包含下划线的字段的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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