Skip to content

Instantly share code, notes, and snippets.

@levmyshkin
Created November 19, 2021 14:13
Show Gist options
  • Save levmyshkin/84b32a6f0ae77a2c3d5bf889e82ccfff to your computer and use it in GitHub Desktop.
Save levmyshkin/84b32a6f0ae77a2c3d5bf889e82ccfff to your computer and use it in GitHub Desktop.
Working with the database in Drupal
<?php
// Select
// Get single value:
$query = \Drupal::database()->select('node_field_data', 'n');
$query->addField('n', 'nid');
$query->condition('n.title', 'About Us');
$query->range(0, 1);
$nid = $query->execute()->fetchField();
// Get entry in array:
$query = \Drupal::database()->select('node_field_data', 'n');
$query->fields('n', ['nid', 'title']);
$query->condition('n.type', 'page');
$query->range(0, 1);
$vegetable = $query->execute()->fetchAssoc();
// You also can use ->fetchObject(), ->fetchAll() to get entry in object.
//Using LIKE in query:
$query = \Drupal::database()->select('node_field_data', 'n');
$query->fields('n', ['nid', 'title']);
$query->condition('n.type', 'page');
$query->condition('n.title', $query->escapeLike('About') . '%', 'LIKE');
$vegetable = $query->execute()->fetchAllKeyed();
// Select query with JOIN:
$query = \Drupal::database()->select('node_field_data', 'n');
$query->fields('n', ['nid', 'title']);
$query->addField('u', 'name');
$query->join('users_field_data', 'u', 'u.uid = n.uid');
$query->condition('n.type', 'page');
$vegetable = $query->execute()->fetchAllAssoc('nid');
// Insert
$query = \Drupal::database()->insert('flood');
$query->fields([
'event',
'identifier'
]);
$query->values([
'My event',
'My indentifier'
]);
$query->execute();
//You can call values() several times to insert multiple records at a time.
// Update
$query = \Drupal::database()->update('flood');
$query->fields([
'identifier' => 'My new identifier'
]);
$query->condition('event', 'My event');
$query->execute();
// Upsert
$query = \Drupal::database()->upsert('flood');
$query->fields([
'fid',
'identifier',
]);
$query->values([
1,
'My indentifier for upsert'
]);
$query->key('fid');
$query->execute();
// Upsert
$query = \Drupal::database()->upsert('flood');
$query->fields([
'fid',
'identifier',
]);
$query->values([
1,
'My indentifier for upsert'
]);
$query->key('fid');
$query->execute();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment