Yii2 model get method for field containing undersc

2019-08-11 09:20发布

Model name: listing; Field name: contact_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.

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.

2条回答
来,给爷笑一个
2楼-- · 2019-08-11 09:37

You can override the afterFind() method for your desired model and override the default value , or format the default value to your desired format. You can override the method by adding the below into your model Listing.

Lets say we need to format the default contact name which is saved like rich-harding in the table and we will format it as Rich Harding

public function afterFind() {
    parent::afterFind();
    $names=explode("-",$this->contact_name);
    $this->contact_name=implode(" ", array_map('ucfirst',$names));
}
查看更多
地球回转人心会变
3楼-- · 2019-08-11 09:40

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. Object properties.
  2. Attributes from database.
  3. Getters/setters (including relations).

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.

查看更多
登录 后发表回答