简体   繁体   中英

yii2 not saving all fields

I have this User model:

  public $id;
    public $username;
    public $name;
    public $password;
    public $authKey;
    public $accessToken;

and this Form model

  class SignupForm extends Model

{
    public $username;
    public $name;
    public $email;
    public $password;
    public $fio;
    public $phone;

And I try to save:

$user = new User();
            $user->username = $this->username;
            $user->name = $this->name;
            $user->email = $this->email;
            var_dump($this->username);
            var_dump($user->username);
            var_dump($this->name);
            var_dump($user->name);

            $user->save(false);

But in the database table this only saves the email field. All data in var_dump are correct.

From here :

Turns out that if you declare public attributes in your ActiveRecord model, they obscure the automatic attributes that are created by AR. Data gets assigned to your obscuring attributes but doesn't get sent into the database.

You can also use the model's attributes() function to declare your model fields, and set validation on the fields using the rules() function.

Example:

public function attributes()
{
    return [
        'id',
        'username',
        'name',
        'email',
    ];
}

public function rules()
{
    return [
        ['id', 'safe'],
        [['username', 'name', 'email'], 'required'],
        [['username', 'name', 'email'], 'string'],
    ];
}

For more information and examples, please check out the documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM