- (11/14) Getting output from shell_exec() at all timesTAGS:Web ProgrammingWeb Server Admin
- (06/12) View Layer - Getting count of Entities in View in Cakephp 3TAGS:CakephpCake3
- (05/23) Changing URL in beforeRedirect() in Component - Cakephp 3TAGS:CakephpCake3Web Programming
- (01/28) Foundation CSS Framework ResourcesTAGS:FoundationCss
- (01/27) Change View File from Controller in CakePHP 3TAGS:CakephpCake3UsageWeb Programming
- (01/13) Loading Model/Table Anywhere in Cake3TAGS:Cake3Cakephp
- (10/06) CURL PHP 5.5 Issue on Windows (Using Twilio SDK)
Subscribe to my feed
saveAll() to save multiple records in 1 model
Posted on 04/17/2009 at 09:58 am by Kevin Wentworth
Viewed 12,006 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:
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.  => array,  => 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.