ActiveRecord не работает
ActiveRecord не работает
Добрый день.
Пытаюсь написать что-нибудь на basic. Написал 3 строчки и те не работают.
$user = new User();
$user->user_name = 'test';
$user->save();
Получаю ошибку: null value in column "user_name" violates not-null constraint
Пытался присвоить через attributes и через конструктор, результат тот же, при записи user_name равно null.
субд postgres
Может кто-нибудь уже сталкивался с такой проблемой?
Пытаюсь написать что-нибудь на basic. Написал 3 строчки и те не работают.
$user = new User();
$user->user_name = 'test';
$user->save();
Получаю ошибку: null value in column "user_name" violates not-null constraint
Пытался присвоить через attributes и через конструктор, результат тот же, при записи user_name равно null.
субд postgres
Может кто-нибудь уже сталкивался с такой проблемой?
-
- Сообщения: 977
- Зарегистрирован: 2014.08.27, 21:54
Re: ActiveRecord не работает
в basic нет user_name.
https://github.com/yiisoft/yii2-app-bas ... s/User.php
Если Вы делали что-то свое - так показывайте всю модель.
https://github.com/yiisoft/yii2-app-bas ... s/User.php
Если Вы делали что-то свое - так показывайте всю модель.
Re: ActiveRecord не работает
я изменил модель User заменил extends \yii\base\BaseObject на extends \yii\db\ActiveRecord, потому-что по другому никак
добавил необходимые для ActiveRecord методы
изменил идентификатор атрибута, был username стал user_name
весь код выкладывать не вижу смысла, 3 строки которые указаны выше вообще из другой модели
но не работает именно $user->save(), потому-что при записи $user->attributes игнорируются как будто они пустые
добавил необходимые для ActiveRecord методы
изменил идентификатор атрибута, был username стал user_name
весь код выкладывать не вижу смысла, 3 строки которые указаны выше вообще из другой модели
но не работает именно $user->save(), потому-что при записи $user->attributes игнорируются как будто они пустые
Re: ActiveRecord не работает
Что значит
Код модели выложите.
?добавил необходимые для ActiveRecord методы
изменил идентификатор атрибута
Код модели выложите.
Чтобы правильно задать вопрос, нужно знать бо́льшую часть ответа. Роберт Шекли.
Re: ActiveRecord не работает
<?php
namespace app\models;
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $user_name;
public $password;
public $auth_key;
public $access_token;
public static function getDb()
{
// использовать компонент приложения "db"
return \Yii::$app->db;
}
public static function tableName()
{
return '{{users}}';
}
/**
* @return array customized attribute labels
*/
public function attributeLabels()
{
return [
'user_name' => 'Имя для входа',
'password' => 'Пароль',
];
}
/**
* Finds an identity by the given ID.
*
* @param string|int $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* Finds an identity by the given user_name.
*
* @param string $user_name the name to be looked for
* @return IdentityInterface|null the identity object that matches the given name.
*/
public static function findByUsername($user_name)
{
return static::findOne(['user_name' => $user_name]);
}
/**
* {@inheritdoc}
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
/**
* {@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)
{
return $this->password === $password;
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->auth_key = \Yii::$app->security->generateRandomString();
}
return true;
}
return false;
}
}
namespace app\models;
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public $id;
public $user_name;
public $password;
public $auth_key;
public $access_token;
public static function getDb()
{
// использовать компонент приложения "db"
return \Yii::$app->db;
}
public static function tableName()
{
return '{{users}}';
}
/**
* @return array customized attribute labels
*/
public function attributeLabels()
{
return [
'user_name' => 'Имя для входа',
'password' => 'Пароль',
];
}
/**
* Finds an identity by the given ID.
*
* @param string|int $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
*/
public static function findIdentity($id)
{
return static::findOne($id);
}
/**
* Finds an identity by the given user_name.
*
* @param string $user_name the name to be looked for
* @return IdentityInterface|null the identity object that matches the given name.
*/
public static function findByUsername($user_name)
{
return static::findOne(['user_name' => $user_name]);
}
/**
* {@inheritdoc}
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
/**
* {@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)
{
return $this->password === $password;
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($this->isNewRecord) {
$this->auth_key = \Yii::$app->security->generateRandomString();
}
return true;
}
return false;
}
}
Re: ActiveRecord не работает
Правила валидации добавь
Re: ActiveRecord не работает
Удалите из модели
Лучше сгенерируйте модель gii а потом в ней реализуйте IdentityInterface
Код: Выделить всё
public $id;
public $user_name;
public $password;
public $auth_key;
public $access_token;
Чтобы правильно задать вопрос, нужно знать бо́льшую часть ответа. Роберт Шекли.
Re: ActiveRecord не работает
добавил, не помогло
Re: ActiveRecord не работает
someweb писал(а): ↑2018.10.10, 17:30 Удалите из моделиЛучше сгенерируйте модель gii а потом в ней реализуйте IdentityInterfaceКод: Выделить всё
public $id; public $user_name; public $password; public $auth_key; public $access_token;
Чтобы правильно задать вопрос, нужно знать бо́льшую часть ответа. Роберт Шекли.