Yii2 non-DB (or virtual) attribute isn't populated during massive assignment?

百般思念 提交于 2019-12-12 02:59:12

问题


I've defined a virtual attribute:

class ContactForm extends Model {

    public $name; // is not a DB field

I've noticed that it is not populated during massive assignment (after submitting the form, in $model->load($_POST)). Can it be somehow populated along with DB attributes? Or am I doing something wrong that is not populated however it should be? Thanks!


回答1:


Docs: Massive Assignments

Like normal models, Active Record instances also enjoy the massive assignment feature. Using this feature, you can assign values to multiple attributes of an Active Record instance in a single PHP statement, like shown below. Do remember that only safe attributes can be massively assigned, though.

Docs: Safe Attributes

For this reason, a special validator aliased safe is provided so that you can declare an attribute to be safe without actually validating it. For example, the following rules declare that both title and description are safe attributes.

You have to do some sort of validation on your attribute, if you don't have any validation needs - define it as safe.

public function rules()
{
    return [
        [['name'], 'safe'],
    ];
}


来源:https://stackoverflow.com/questions/35543500/yii2-non-db-or-virtual-attribute-isnt-populated-during-massive-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!