S
S
Sergey Beloventsev2016-07-29 15:28:35
Yii
Sergey Beloventsev, 2016-07-29 15:28:35

How to disable update from save() when looping?

Actually here is the code

$model = new Image();
     if ($model->load(Yii::$app->request->post())) {
     	foreach($files->files as $file){
      		$years=date('Y');
                    $mounts=date('m');
                    $model->path = $path.'/'.$years.'/'.$mounts.'/';
                    $model->name = $files_to;
                    $model->title_alt=$altNames." ".$count;
                    $model->save();
                     $file->saveAs(Yii::getAlias('@frontend/web/image/') . $path . '/' . $years . '/' . $mounts . '/' . $files_to);
                     }
    }

this is how it looks in the debugger
INSERT INTO `fl_image` (`title_alt`, `for_home`, `id_film`, `path`, `name`) VALUES ('Тарзан. Легенда 0', 0, 1, 'film/2016/07/', '12089457.jpg')
    UPDATE `fl_image` SET `title_alt`='Тарзан. Легенда 1', `name`='Space-Desktop.jpg' WHERE `id`=2180
    UPDATE `fl_image` SET `title_alt`='Тарзан. Легенда 2', `name`='xJtqzdQr7RE.jpg' WHERE `id`=2180

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2016-07-29
@Sergalas

the save() method is designed so that if there is a record, it will update it, if there is no record, it will add it. If you only need to add an entry, use the $model->insert() method;
But in general, inserting records into the database in a loop is evil, use a mass insert better

S
Slava Kryvel, 2016-07-29
@kryvel

I think your logic is not correct. Since your code simply overwrites the data for one object in a loop.
Specify what exactly you are trying to do. Create multiple posts with same id but different title_alt i name ? Or you need to store an array from title_alt i name for one id

A
Andrew, 2016-07-29
@mhthnz

When writing batch data, in each iteration of the loop, you must create a new instance of your model. You can create a saveAll() method in the model and save it all in a loop. + when saving batch data, you must use transactions, if you have an error saving some data, then some of the data will be written, and some will not. Transaction solves this problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question