Work with database in Drupal 8

Drupal 8 database

For creating database queries in Drupal 8, we should add dependency to ´Drupal\Core\Database\Connection´ class inside our class.

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
<?php
namespace Drupal\our_custom_module_name;
use Drupal\Core\Database\Connection;
/**
* Our class, where we will communicate with database.
*/
class LetsTalkWithDatabase {
/**
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* Construct.
*/
public function __construct(Connection $database) {
$this->database = $database;
}
/**
* Create function.
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('database')
);
}
}

The Query with condition

1
2
3
4
5
6
$nodes = $this->database('node', 'n')
->fields('n', array('nid', 'title'))
->condition('n.type', 'page')
->condition('n.uid', 1)
->execute()
->fetchAll();

The Query with joining

1
2
3
4
5
$query = $this->database('node', 'n');
$query->innerJoin('users', 'u', 'n.uid = u.uid');
$query->fields('n', array('title'));
$query->fields('u', array('name'));
$nodes = $query->execute()->fetchAll();
Share Comments