Build-in query persist? Is there a default Drupal 8 database persist function? Like as for Doctrine.

for($i=1;$i&lt;100;$i++) {
    $query-&gt;persist();
}

$query-&gt;flush();


I want to collect first a lot of data and bulk send it to the database.

The code I am using now is the following.

$db = \Drupal::database();    
foreach($response-&gt;customer_products as $itemCode) {
    $productNode = $this-&gt;loadObjectProduct($itemCode);
    $db-&gt;insert('customer_product')
           -&gt;fields([
              'card_code' =&gt; $cardCode,
              'item_code' =&gt; $productNode-&gt;id()
           ])
       -&gt;execute();
}


That requires too much memory, and it fires a lot of queries.

Is there some way to collect the queries and bulk-send it to the database?
It's possible to stuff more values into a custom insert (or merge) by using the values method. This isn't comparable to the persist functionality, and can only be used in limited scenarios such as a single table. A more complex storage scenario, such as with entities, would not be possible as a single entity save operation could be writing to multiple tables (unless someone rewrote a custom entity storage layer).

Also, I am not sure what the loadObjectProduct exactly does in your code, but this seems to be loading node entities. It would probably be best to use an Entity Query::condition and fetch back multiple entities.

Finally you need to use an array map/reduce to map the values.

Something like the following pseudo-code:

// Using Database static method from \Drupal\Core\Database\Database.
$database = Database::getConnection();
// Assumes loadObjectProduct is refactored.
$nodes = $this-&gt;loadObjectProducts($itemCode);
// I tend to think backwards about this sort of thing. :-)
$values = array_reduce($nodes, function (&amp;$result, $productNode) use ($cardCode) {
  $result[] = [
    'card_code' =&gt; $cardCode,
    'item_code' =&gt; $productNode-&gt;id(),
  ];
  return $result;
}, []);

try {    
  $database-&gt;insert('customer_product')
    -&gt;fields(['card_code', 'item_code'])
    -&gt;values($values)
    -&gt;execute();
}
catch (DatabaseWrapperException $e) {
  // Catch errors
}