Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 - multiple insert in one query

I assumed doctrine2 would optimize my query to give the best performance for any database transactions.

I was inserting approximately 500 records in a database table, and i came to notice it created 500+ query to insert the records (one query per record), i am wondering, why wouldn't doctrine make use of multiple inserts to insert all record in one shot, wouldn't this reduce load and optimize the query? am i missing something about this behavior from doctrine?

Here is the code i am using for insertion:

$content = json_decode($response->getBody());
$em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
foreach ($content as $value) {
    $log = new log();
    $log->fromArray($value);
    $em->persist($log);
}
$em->flush();

Update1:
Here is the content of fromArray() as requested, the purpose of this function is to basically consolidate values to class property from an array:

/**
 * Map parameters with class property.
 *
 * @param $array array
 * @access public
 * @return $this
 */
public function fromArray(array $array)
{
    foreach ($array as $property => $value) {
        $method = 'set'.ucwords($property);
        $this->$method($value);
    }
    return $this;
}

Here is content of $content:

Array
(
    [0] => stdClass Object
    (
        [id] => 111
        [guid] => aaaa-bbbb-cccc
        [wid] => 100
        [pid] => 101
        [start] => 2014-11-22T12:44:44+00:00
        [stop] => 2014-11-22T15:23:11+00:00
        [duration] => 9507
        [description] => Log description
        [tags] => Array
            (
                [0] => test
            )
        [at] => 2014-11-24T07:28:09+00:00
        [uid] => 51
    )
    [1] => stdClass Object
    (
        [id] => 112
        [guid] => dddd-eee
        [wid] => 100
        [pid] => 101
        [billable] => 
        [start] => 2014-11-22T15:35:07+00:00
        [stop] => 2014-11-22T15:45:21+00:00
        [duration] => 614
        [description] => Lorem description
        [tags] => Array
            (
                [0] => php
                [1] => pm
            )
        [at] => 2014-11-24T04:35:30+00:00
        [uid] => 51
    )
)
like image 382
Ibrahim Azhar Armar Avatar asked May 03 '26 18:05

Ibrahim Azhar Armar


1 Answers

Please take a look at this document. At every iteration, Doctrine creates one insert ... query for you, after all, when you call flush(), Doctrine sends all those insert queries to db at one time inside a loop(using a mechanizm like foreach(queries as query) { run->query.. }) In your case any of these queries are inserts, so, as i stated in comment, there is no abnormal situation in your case. ORM may not be suitable for all cases.

like image 138
ilhnctn Avatar answered May 05 '26 08:05

ilhnctn