$model = new FormUnosh(); if ($model->load(Yii::$app->request->post())) { $sql = 'SELECT NagrNomer FROM FormUnosh'; $provg = FormUnosh::findBySql($sql)->all(); if($provg){ foreach ($provg as $item){ if ($model->NagrNomer!=$provg){ $model->save(); return $this->redirect(['view', 'id' => $model->id]); } else { throw new NotFoundHttpException('Не верно!'); } } } return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } - 2what does it mean to pass? if this condition then add it to the findbysql method. and now you have the entire table in the model (many rows, so it’s not clear what id you are requesting), but there should be only one entry with one id. - perfect
- I meant that while adding a record, it receives data from NagrNomer, and if during the addition of a record it finds an already given number, it gives an error. - Sever
- and the entry is not added accordingly. - Sever
2 answers
In general, your logic is not clear what you are doing, but apparently you had better write like this:
$model = new FormUnosh(); if ($model->load(Yii::$app->request->post())) { $isInBD = FormUnosh::find()->where(['NagrNomer' => $model->NagrNomer])->count(); if ($isInBD > 0) { $model->save(); } else { throw new NotFoundHttpException('Не верно!'); } return $this->redirect(['view', 'id' => $model->id]); } return $this->render('create', [ 'model' => $model, ]); In general, it is better to bring this into the model in the validator. And even better to think about the logic of the application - in my opinion something is lame in you in it.
- Forgot to unsubscribe decided the same design, but thanks anyway. - Sever
First, you can immediately write to the sql where clause and not pull all the records from the database. As long as you have few of them, everything is fine. But when you have a million of them and a thousand users turn to it, your code will collapse like a house of cards.
Secondly, the application logic is wrong, here it is.
foreach ($provg as $item){ if ($model->NagrNomer!=$provg){ $model->save(); return $this->redirect(['view', 'id' => $model->id]); } else { throw new NotFoundHttpException('Не верно!'); } } The question is, what happens when the code reaches return? The answer is that it will exit the cycle and save the changes. Therefore, this code will take the very first element, then it will rest on return and no iteration on all products will happen.