Database Merge, Insert or Update if exist. | Drupal 8

Database Merge, Insert or Update if exist.

Submitted by editor on Sat, 11/28/2015 - 10:56

How to merge (Insert or Update if exist) On drupal 8.

Merge SQL data base: Insert field or update if exist

$con = Database::getConnection();
$query = $con->merge('the_table_name')
    ->key(array('ref' => $ref))
      'ref' => $ref,
      'count' => 1,
      'create' => time(),
      'update' => time(),
      'name' => $name,
      'status' => $status,
   ->expression('count', 'count + :inc', array(':inc' => 1));
$return_value = $query->execute();


Chris (not verified)

Mon, 12/05/2016 - 19:24

This is super cool and to-the-point; however, you've got a semi-colon after updateFields(); ... but then an ->expression() call. 

For my needs I didn't need the ->expression so just removed it. 


Tue, 12/06/2016 - 12:00

In reply to by Chris (not verified)

Hi Chris, Thank you for the correction, If you want to add expression or any other method, you can also do like:
$query ->expression('count', 'count + :inc', array(':inc' => 1));

Chris Happy (not verified)

Tue, 11/07/2017 - 06:55

Warning: don't use the column name `created`. It has caused a MySQL error in Drupal 8.4.0:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'create ...


Add new comment