MainelyDesign.com Blog

saveAll() to save multiple records in 1 model

Posted on 04/17/2009 at 09:58 am by Kevin Wentworth
Viewed 18,947 times | 0 comments

I ran into another issue on something I thought would be simple: saving multiple records with the saveAll() command.  In case you don't know about it, saveAll() is one of the best functions in CakePHP.  It automatically supports transactions, HABTM saves, and certainly saves a lot of typing for almost every type of save you want to do.

There are a few gotchas.  Here what I ran into:

  • Inserting/creating new rows in the database, don't forget $this->ModelName->create() //no duh, right? Well, I forgot it.
  • Sending the right data to saveAll.  $this->saveAll($this->data['ModelName']);

At first I was trying to do a $this->ModelName->saveAll($this->data).  It wasn't working.  It would start the transaction and commit absolutely nothing.  What gives?  It turns out with saveAll() you need to send an indexed array of the data you want to insert.  In my case I have security enabled so the first indexed array was the form token and hash.  No wonder it wasn't saving anything.

The solution is to specifically send $this->saveAll($this->data['ModelName']); not $this->saveAll($this->data);  It seems obvious but had me sweating for a little while.

I also wanted to touch on the format of the data array needed for saveAll().  I'm always searching around for this and can't ever remember where I found my answer last time... so here it is:

The data array needs to be in an indexed array format, with the model name as the parent key:

  1. $data = array('ModelName' => array(0 => array('id' => 1, 'name' => 2, 'etc' => 'n'), 1 =>  array('id' => 1, 'name' => 2, 'etc' => 'n')));

Another note on multiple records- you don't need to start your indexed array at 0.  I usually loop through a set number of times and like to start labeling 'Enter Client 1', 'Enter Client 2', etc. using the index to output the current Client #, for instance.  In this case my indexed array starts at 1, not 0, with no issues.  I also have had non-sequential indexed arrays (i.e. [1] => array, [3] => array) save with no problem.  Man, I love Cake!

Thanks to http://blog.matsimitsu.nl/code/186/saveall-for-cakephp-part-3 and the comments by BrandonKoz.

Cheers,

-Kevin Wentworth

Bookmark and Share

Tags for saveAll() to save multiple records in 1 model

Cakephp | Database | Saveall | Habtm

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design