E
E
Elios2015-10-29 23:34:27
Yii
Elios, 2015-10-29 23:34:27

YII2 How to write to DB in a loop using AR?

I want to make it possible to write a list, for this I divide the received post into a cycle of line breaks, I submit a list to the post:
21e49c19936045c197a6806b40427eb0.JPG
Here is the action code:

$model = new Word();
        if ( $model->load(Yii::$app->request->post()) ) {
            if( strpos( $model->word_name, "\n" ) ) {  //Если есть переносы строк в посте
                $model->word_name = explode("\n", $model->word_name);  //Разбивает строку на массив
                foreach ($model->word_name as $word_name) {
                    $model->word_name = trim($word_name);
                    echo "<pre>";
                    echo "word_name: ";
                    var_dump($model->word_name);
                    echo "projekt_id: ";
                    var_dump($model->projekt_id);
                    echo "group_id: ";
                    var_dump($model->group_id);
                    echo "status_id: ";
                    var_dump($model->status_id);
                    echo "<pre>";
                    $model->save(); // Делаем запись в цилке
                }
            } else {
                $model->save();
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

The result of the code is this:
word_name: string(25) "Новый запрос 1"
projekt_id: string(1) "2"
group_id: string(1) "3"
status_id: string(1) "1"
word_name: string(25) "Новый запрос 2"
projekt_id: string(1) "2"
group_id: string(1) "3"
status_id: string(1) "1"
word_name: string(25) "Новый запрос 3"
projekt_id: string(1) "2"
group_id: string(1) "3"
status_id: string(1) "1"

Actually, that's what I wanted, but only the last entry from the list is entered into the database, why is this happening? And how actually to make all records?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrei, 2015-10-29
@strelov1

You always have the same model... if you do it in a cycle and it's new, then create it.. if it's not new, then get it through a request, but in general AR in a cycle is not a good practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question