How to write custom query in Drupal 8?

Member

by domenico , in category: PHP Frameworks , 2 years ago

How to write custom query in Drupal 8?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by dedrick , 2 years 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.

by herminia_bruen , a year ago

@domenico 

It's important to note that using the Drupal::database() service directly is considered bad practice because it bypasses Drupal's caching system and can cause performance issues. Instead, you should use dependency injection to inject the database service into your custom code.


Here's an example of how to write a custom query using dependency injection:

  1. Create a custom service class, for example, MyCustomQueryService, in a new module or in an existing custom module.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
namespace Drupalmy_moduleServices;

use DrupalCoreDatabaseConnection;

/**
 * MyCustomQueryService service.
 */
class MyCustomQueryService {

  protected $database;

  /**
   * Constructor.
   */
  public function __construct(Connection $database) {
    $this->database = $database;
  }

  /**
   * Custom query method.
   */
  public function customQuery() {
    // Build and execute the SELECT query.
    $query = $this->database->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.
      // ...
    }
  }

}


  1. Register the service in your module's .services.yml file:
1
2
3
4
services:
  my_module.my_custom_query_service:
    class: Drupalmy_moduleServicesMyCustomQueryService
    arguments: ['@database']


  1. Use the service in your custom module or code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use DrupalCoreDependencyInjectionContainerInjectionInterface;
use SymfonyComponentDependencyInjectionContainerInterface;

/**
 * Custom class.
 */
class MyCustomClass implements ContainerInjectionInterface {

  protected $customQueryService;

  /**
   * Constructor.
   */
  public function __construct(MyCustomQueryService $customQueryService) {
    $this->customQueryService = $customQueryService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('my_module.my_custom_query_service')
    );
  }

  /**
   * Custom method that uses the custom query service.
   */
  public function customMethod() {
    $this->customQueryService->customQuery();
  }

}


By using dependency injection, you can now access the custom query service in your custom class or module, ensuring that you're using Drupal's best practices and benefiting from its caching system.