H
H
hollanditkzn2017-05-10 10:58:47
Yii
hollanditkzn, 2017-05-10 10:58:47

How to save data to database?

I use the yii2-multiple-input widget, I don’t understand a little in the documentation how to save data in the database with multiple values
​​​​in the guide if you need everything to view the model and the whole picture
Implemented like this but in the end

$models = [new Custom()];
$request = Yii::$app->getRequest();

Model::loadMultiple($models, Yii::$app->request->post())) {
            $data = Yii::$app->request->post('Custom', []);
            foreach (array_keys($data) as $index) {
                $models[$index] = new Custom();
            }

Tried to add $models->save() and got error Call to a member function save() on array
And tried $models[$index]->save(); it does not save
Tried to display an error
if(!$model->save()){
                Yii::warning($models[$index]->getErrors());
                }
But it didn't work either. Requests come in the form
Custom[0][product]:Handles
Custom[0][number]:10
how to solve this problem?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2017-05-10
@hollanditkzn

// создаем на каждый набор данных в массиве модель
$data = Yii::$app->request->post('Custom', []);
$models = [new Custom()];
foreach (array_keys($data) as $index) {
    $models[$index] = new Custom();
}
// загружаем данные из запроса в массив созданных моделей
if (Model::loadMultiple($models, Yii::$app->request->post())) {
    foreach ($models as $model) {
        //сохраняем данные
        $model->save();
    }
}

M
Maxim Timofeev, 2017-05-10
@webinar

Call to a member function save() on array

Says you are calling save() on an array, and only AR objects have a save() method. Apparently, you need to iterate over the array, it will contain objects, to which you can apply the save method

B
Boris Yakushev, 2017-05-10
@za4me

yiiframework.domain-na.me/doc/guide/2.0/en/structu...
yiiframework.domain-na.me/doc/guide/2.0/en/db-acti...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question