Having recently been building an import tool for our latest site at work, I was reminded of a very important thing to remember when creating rows in CakePHP.
If you create more than one row in a loop, you must call create() before you call save().
foreach ($rows as $row) {
$this->Model->create();
$this->Model->save($row);
}
The create function will reset the model internals associated with saving rows. If you don’t call it, your subsequent calls to save() will merely update the first one added.
It’s important to note that create() doesn’t actually create the row, it just tells Cake that we’re about to create one.


Comments
There are 2 responses to “Insert rows in a loop in CakePHP” (Subscribe by RSS)
00:38
abba bryant
Or, use Model::saveAll…
08:50
Ric
As abba says, you could use Model::saveAll().
However, that wouldn’t work in my project because I wasn’t doing the same thing to every row, some needed to be added, some updated and some removed based on other factors.