Score:0

How can I increment and save an integer value in a single operation to avoid race conditions?

km flag

How can I increment and save an integer value in a single operation to avoid race conditions?

With MySQL, I could use the following query.

INSERT into mytable (logins)
 SELECT max(logins) + 1
 FROM mytable

I am currently using the following code.

$query = \Drupal::entityQuery('node')->condition('type', 'bond')
  ->condition('field_para_identifier.entity:paragraph.field_bond_pending_id', 'NULL', 'IS NOT NULL')
  ->sort('field_para_identifier.entity:paragraph.field_bond_pending_id', 'DESC')
  ->range(0, 1);
$results = $query->execute();
$biggest_pending_id_entity_id = array_pop($results);
$next_pending_id = 1;

if ($biggest_pending_id) {
  $next_pending_id = intval($biggest_pending_id) + 1;
}

$identifier = $bond->get('field_para_identifier')->getValue();
$identifierParagraph = Paragraph::load($identifier[0]['target_id']);
$identifierParagraph->set('field_bond_pending_id', $next_pending_id);
$identifierParagraph->save();
Jaypan avatar
de flag
You can use a transaction with a rollback: https://www.drupal.org/docs/drupal-apis/database-api/database-transactions
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.