I'm new to Doctrine and there are still some blurred areas for me. In this case I'm inserting new record in the database using a loop and the entity manager. It works fine but I noticed that Doctrine make one insert query by entity, which can become pretty huge.
Using Doctrine2 and Symfony 2.3, I would like to know how we can set it up so it would make only 1 insert query with all the values in it (we are talking of 1 entity only of course).
What I mean is changing this :
INSERT INTO dummy_table VALUES (x1, y1)
INSERT INTO dummy_table VALUES (x2, y2)
Into
INSERT INTO dummy_table VALUES (x1, y1), (x2, y2)
Here is my code :
$em = $this->container->get('doctrine')->getManager();
foreach($items as $item){
$newItem = new Product($item['datas']);
$em->persist($newItem);
}
$em->flush();
I have not tested it but it seems possible to do this with a collection.
Of course you should have the add in the loop.
You can try this fork https://github.com/stas29a/doctrine2. It implements exactly what you want. I tested it in MySQL and it works fine and 5 times faster than that batch processing. This fork get a first inserted id and increments it in php for getting other id's. It works for most cases but not in all. So you need to understand what are you doing when using this fork.
You can use
executeUpdate($query, array $params = array(), array $types = array())
method ofDriverConnection
interface to perform this action. However it's little tricky to bind multiple parameters.Data:
Bulk update method:
According to this answer, Doctrine2 does not allow you to combine multiple INSERT statements into one:
You can read more about Doctrine2 batch processing here: http://www.doctrine-project.org/blog/doctrine2-batch-processing.html
You can either switch to DBAL or resort to processing your data in small batches by flushing your entity manager after a set amount of inserts: