Сохраняет пустые данные с помощью model->save() в Yii2

703
20 марта 2017, 11:02

При регистрации в базу данных сохраняется пустая строка когда выполняю $user->save(). Причём валидацию проходит нормально. Код модели User:

<?php
namespace app\models;
use yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
public $id;
public $username;
public $email;
public $password;
public $phone_number;
public $authkey;

public static function tableName(){
    return 'user';
}
public function rules(){
    return [
        [['id','authkey'],'safe'],
        [['username', 'password','email'], 'required'],
        [['email'], 'email'],
        [['phone_number'],'string', 'max' => 13],
        [['username'], 'string', 'max' => 16],
    ];
}
/**
 * @inheritdoc
 */
public static function findIdentity($id)
{
    return static::findOne($id);
}
//Не нужен
public static function findIdentityByAccessToken($token, $type = null)
{
    throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
 * Finds user by username
 *
 * @param string $username
 * @return static|null
 */
public static function findByUsername($username)
{
    return static::find()->where('username = :username',[':username' => $username])->one();
}
/**
 * @inheritdoc
 */
public function getId()
{
    return $this->id;
}
/**
 * @inheritdoc
 */
public function getAuthKey()
{
    return $this->authKey;
}
/**
 * @inheritdoc
 */
public function validateAuthKey($authKey)
{
    return $this->authKey === $authKey;
}
/**
 * Validates password
 *
 * @param string $password password to validate
 * @return bool if password provided is valid for current user
 */
public function validatePassword($password)
{
    $hash = $this->password;
    return Yii::$app->getSecurity()->validatePassword($password,$hash);
}
public function beforeSave($insert){
    if (parent::beforeSave($insert)){
        if($this->isNewRecord){
            $this->authkey = Yii::$app->getSecurity()->generateRandomString();
        }
        return true;
    }
    return false;
}
}

Код модели SignupForm:

<?php
namespace app\models;
use Yii;
use yii\base\Model;
use app\models\User;

class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;
    public $confirmPassword;
    public $phone_number;

public function rules()
{
    return [
        [['username','email', 'password','confirmPassword'], 'required'],
        ['email', 'email'],
        ['phone_number', 'string', 'max' => 13],
        ['password', 'string', 'min' => 6],
        ['confirmPassword', 'compare', 'compareAttribute' => 'password']
    ];
}
public function signup()
{
    $new_user = new User();
    $new_user->username = $this->username;
    $new_user->email = $this->email;
    $new_user->phone_number = $this->phone_number;
    $new_user->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
    Yii::trace($new_user->attributes;
    Yii::trace($new_user->getDirtyAttributes());
    Yii::trace($new_user->getOldAttributes());
    $status = $new_user->save();
    Yii::trace($status);
    return $status;
}
}

В отладке я увидел следующее:

То есть Dirty атрибутов нету вообще, хотя я создал новый обьект с помощью new User(). В итоге Yii смотрит что в Dirty атрибутах пусто а значит и менять ничего не надо. В итоге в базе данных я получаю пустую строку.

Вот вывод базы данных:

В beforeSave когда оно заходит то isNewRecord выполняется, то есть обьект считается новой записью и добавляется authKey, но вот только ничего не сохраняется.

Answer 1

Ваша ошибка в том, что вы добавили одноимённые со столбцами таблицы БД публичные свойства атрибутов в модель User, тогда как ActiveRecord, от которого наследуется модель, сам их забирает из rules[], соответственно он не знает с чем ему работать - с виртуальными свойствами или с БД.

READ ALSO
Получить имена методов

Получить имена методов

Вывод из var_dump()

262
Замена символов в URL на Yii2

Замена символов в URL на Yii2

В Url manager написал простое правило для URL товаров с категориями

414
Как сделать постраничный вывод?

Как сделать постраничный вывод?

Подскажите что надо сделать для постраничного вывода?

229
Сосчитать многомерный массив

Сосчитать многомерный массив

Массив формируется таким образом:

283