How to write custom query in Drupal 8?

Member

by domenico , in category: PHP Frameworks , a year ago

How to write custom query in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , 9 months ago

@domenico 

To write a custom query in Drupal 8, you can use the Drupal::database() service to get a database connection object and then use that object to build and execute a query.


Here is an example of how you can use this service to execute a custom SELECT query:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Get a database connection object.
$connection = Drupal::database();

// Build and execute the SELECT query.
$query = $connection->select('node', 'n');
$query->fields('n', ['nid', 'title']);
$query->condition('n.type', 'article');
$query->range(0, 10);
$results = $query->execute();

// Fetch the results.
$nodes = $results->fetchAll();

// Do something with the results.
foreach ($nodes as $node) {
  // Process the node.
  // ...
}


You can also use the insert, update, and delete methods on the query object to build and execute INSERT, UPDATE, and DELETE queries, respectively.


For more information on using the database API in Drupal 8, you can refer to the Database API documentation on Drupal.org.