Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Database Merge, Insert or Update if exist.

By editor , 28 November, 2015
Question

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))
    ->insertFields(array(
      'ref' => $ref,
      'count' => 1,
      'create' => time(),
    ))
    ->updateFields(array(
      'update' => time(),
      'name' => $name,
      'status' => $status,
    ))
   ->expression('count', 'count + :inc', array(':inc' => 1));
$return_value = $query->execute();

Tags

  • Drupal 8
  • Database
  • Add new comment
Database Basic Examples (Select, Merge, Insert ...)

Comments3

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Chris (not verified)

9 years 12 months ago

Thanks!

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. 

  • Reply

editor

9 years 12 months ago

In reply to Thanks! by Chris (not verified)

Thank you for the correction

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));

  • Reply

Chris Happy (not verified)

9 years ago

Warning

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 ...

 

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer