CakePHP saveAll() quick tip

Saving data with Model->saveAll() is really time savior. There is something specifics while saving multiple records of a single model.

The data provided from the form should be in the numerically indexed array of records like this:

Array
(
    [Article] => Array(
            [0] => Array
                (
                            [title] => title 1
                        )
            [1] => Array
                (
                            [title] => title 2
                        )
                )
)

Your code for saving this data with saveAll() should look like this:

$this->Article->saveAll($data['Article']);

Ok, but if you pass only

$this->Article->saveAll($data);

it won’t work. So if you want to save multiple records of a single model provide the proper data. It took me 1/2 hour to detect that this is the problem.

Of course this is written in the CookBook, but somebody need to read it carefully ;)

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca

6 thoughts on “CakePHP saveAll() quick tip

  1. I remember spending about half and hour trying to figure out just this same problem a few months back.

    I don’t think it’s the CookBooks fault, I read the same thing 1-2 times before catching it, more just me not reading what’s right there. Nice to see I’m not the only one who got caught by this :)

  2. Me too! They should really put some kind of comment in the docs about this… Why does it not work as $data?? Because we are not saving to multiple models?

  3. Great tip, thanks. This was exactly what I was looking for. Especially the last part. Got stuck for a while until I finished reading…

  4. Thanks, but had also some different issue. $this->ShopItem->saveAll($data['ShopItem']) didn’t work, but changing $data['ShopItem'] to $this->data['ShopItem'] it worked.

  5. in my application saveAll() method is not working.
    my data in below format.
    Array
    (
    [Article] => Array(
    [0] => Array
    (
    [title] => title 1
    )
    [1] => Array
    (
    [title] => title 2
    )
    )
    )

    and i call the saveAll() like this
    $this->Model->saveAll($data['Article']);
    but it coundt save the data .please some one helpme out.

    Thnaks in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>