Inserting multiple rows in cakephp

Wednesday, February 10, 2010 13:15

I had a situation where I needed to iterate through a list of items and insert new rows for each. I quickly discovered that if you insert an item and then immediately insert another, the item that is inserted next doesn’t insert at all. Instead the previously inserted row was being updated. For example:

$items = array('Item 1','Item 2','Item 3');
foreach ($items as $item) {
  $this->Post->create();
  $this->Post->save(array('Post' => array('title' => $item)));
}

This code will result in a single entry in the posts table: “item 3.” CakePHP inserted “item 1″, but then updates it to become “item 2,” then “item 3″ because $this->Post->id gets the value of the last inserted ID. Normally this functionality is very useful, but in this particular instance it was not. I found was to setting $this->Post->id = false after each insert solved the problem.

  • Share/Bookmark
You can leave a response, or trackback from your own site.

One Response to “Inserting multiple rows in cakephp”

  1. Use a rowing machine says:

    February 21st, 2010 at 1:19 pm

    One can imagine I read it twice. While I am not as skilled on this topic, I tally with your conclusions because they create sense. Thanks and goodluck to you.

Leave a Reply