harikrish
harikrish

Reputation: 2019

cakephp saveall is saving with multiple query

I have an array that is saved into the database using saveall in cakephp. recently i noticed that the array has around 100 set of values and 100 insert queries are run to save this. This is done as a transaction and then later commiting it. Each query takes around 1ms. so 100 queries add up a lot of time. I am sure that there is some ways to do this in one query.

i tried

$this->User->savemany($data)

but there is no change.

is there any other method by which i could save something like this

INSERT INTO users (ID, Value)

VALUES (1, 'First'), (2, 'Second'), (3, 'Third');

thank you

Upvotes: 0

Views: 1361

Answers (1)

James Revillini
James Revillini

Reputation: 132

No, there is not a way to accomplish this without getting into custom SQL or extending AppModel so that it had a method to run optimized INSERT statements in certain situations. **

Keep in mind that you won't always be saving a model's data all by itself. Sometimes you're saving related objects.

For example: Person hasMany Car. When you save multiple Persons, each with an arbitrary number of Car(s), CakePHP needs to get back the ID for each Person record saved before it can associate their Car records in the database.

Like I said, you could extend AppModel and either augment the saveAll method to inspect the structure of the data that's being saved and have it hook off into a custom method that you write to do what you want, but it's probably going to add more to the saveAll method overhead than it's worth.

** The best optimization you can do without a lot of custom coding would be wrapping the saveAll with a transaction so you don't init and commit for each of them. Example:

$this->Model->begin();
$this->Model->saveAll(data);
$this->Model->commit();

Upvotes: 1

Related Questions