Answer the question
In order to leave comments, you need to log in
Why is the save() method not working?
I have a method like this:
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
return true;
}
return false;
}
public function afterSave($insert, $changedAttributes)
{
# Добавляем пользователю группу пользователя
$auth = Yii::$app->authManager;
$user_group = $auth->getRole('user');
$auth->assign($user_group, $this->id);
parent::afterSave($insert, $changedAttributes);
}
$model = Users::findOne(['id'=>1]);
$model->name = 'New name';
$model->save();
//$user = Users::findOne(['id'=>Yii::$app->user->identity->id]);
$user = Users::find()->where(['id' => Yii::$app->user->identity->id])->one();
$user->balance = ($user->balance - $cost);
if (!$order->save() || !$user->update()) {
$response = ['code' => -99, 'text' => 'Произошла неизвестная ошибка, обратитесь в тех поддержку, код ошибки: -99'];
$this->printAPI($response);
} else {
$response = ["code" => 5, "text" => "Заказ №" . $order->id . " успешно создан! ", 'balance' => $user->balance];
$this->printAPI($response);
}
Answer the question
In order to leave comments, you need to log in
You are not validating. See validation rules. Execute in code var_dump($model->errors) перед формой.
AND see errors. If you do not have errors of one model - see another. Whether it's validation or not is easy to check.$model->save(false)
1. You can not write
$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);
$user->update()
in the construction if
, because $user->update() returns not true / false, but the number of changed rows in the database, but in Yii, if the model has not changed, nothing will be updated in the database (why an extra request), just write$user->save()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question