S
S
shanik2017-09-11 16:32:14
Yii
shanik, 2017-09-11 16:32:14

How to properly modify and add Yii data?

how to change and add data correctly?
So that one function can both add new values ​​and change old ones.
At me now there is only an addition and swears on a double.

$floraUser = new floraUser();
$users = Yii::$app->request->post('Flora')['users'];
foreach ($users as $user) {
                        $floraUser->isNewRecord = true;
                        $floraUser->flora_id = $id;
                        $floraUser->user_id = $user;
                        $floraUser->save();
                    }

without it only 1 value is added $floraUser->isNewRecord = true;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-09-11
@shanik

very strange code.
Why at all $floraUser->isNewRecord = true?
And what is the variable that came out of nowhere $id?
Why is the creation of an instance of the FloraUser class outside of the iteration? With a new iteration of the loop, you are working not with a new class, but with an old one. And it already has an id and you just overwrite the same record a bunch of times.
If I understand your idea correctly, it looks like this:

foreach (Yii::$app->request->post('Flora')['users'] as $user) {
                        $floraUser = new FloraUser();
                        $floraUser->flora_id = $id;
                        $floraUser->user_id = $user;
                        if(!$floraUser->save())
                           throw new \yii\web\ErrorException(yii\helpers\Json::encode($floraUser->errors));//это что бы увидеть в дебаге ошибки валидации, можно грохнуть
                    }

and if you shorten it, then this:
foreach (Yii::$app->request->post('Flora')['users'] as $user) {
                        $floraUser = new FloraUser([
                        'flora_id'=>$id,
                        'user_id'=>$user
                         ]);
                        if(!$floraUser->save()) 
                           throw new \yii\web\ErrorException(yii\helpers\Json::encode($floraUser->errors)); //это что бы увидеть в дебаге ошибки валидации, можно грохнуть
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question