S
S
Sergey Beloventsev2016-04-27 13:41:05
Yii
Sergey Beloventsev, 2016-04-27 13:41:05

Why does save() fire once?

there is an array $catID
here are its values

array(2) { 
    	[0]=> string(1) "1" 
    	[1]=> string(1) "2"
    	 }

trying to run it to save via foreach here is the code
foreach($catID as $cat){
                     $catSerial->id_cat=$cat;
                     $catSerial->id_serial=$model->id;
                     $catSerial->save();
                 }

the problem is that save() is processed once the last time why ? And how to make it work twice.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
3
333Serega333 333Serega333, 2016-04-27
@Sergalas

What I would like to say first. Calling the save() method entails executing a query to the database. You are calling this method in a loop, and this is not correct at all. I would recommend doing the desired functionality in a different way.
You can't do sql queries in a loop!!!

S
Slava Kryvel, 2016-04-27
@kryvel

Do you mean it only works once?
Is it only writing the last element? or are recorded all but only at the end?
what primarykey do you have in catSerial ?

M
mitaichik, 2016-04-27
@mitaichik

You most likely have an error in the logic of the above code. It feels like you want to create 2 rows in the db, but the above code will make one and then modify it. You'd better write what you want to do.
It should also be noted: save is called in any case, but it will not always save. For example, if the validation fails, it will not try to save the invalid model to the database.
It is quite possible that you have a unique cat_id validator and a line with this id already exists - save will not save, it will simply return false.
If you are doing something critical, the result of save should always be checked! And either throw an exception, or somehow handle it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question