Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a query in Drupal 8

I am used to using db_select in drupal 7 but now it's deprecated in drupal 8

So, If I need to create a query to list all users from users_field_data table, What should I do?

Do I still use db_select or db_query even though they are deprecated functions? Or create a new controller to extend from "Select class" and make my query?

like image 826
Mina Atia Avatar asked Nov 26 '15 18:11

Mina Atia


People also ask

How do I create a custom query in Drupal 8?

As in the seventh version, Drupal 8 builds the query based on methods such as fields (), join (), condition (), and so on. You can execute the query by calling 'the execute `() method. $query = \Drupal::database()->select('node_field_data', 'nfd'); $query->fields('nfd', ['uid', 'title']); $query->condition ('nfd.

How do I select a query in Drupal 8?

For a field selection use, $query = \Drupal::database()->select('table_name', 'alias') ->fields('alias', ['field1', field2]) ->condition('field3', $condition); $results = $query->execute(); while ($content = $results->fetchAssoc()) { // Operations using $content. }

What is query tag in Drupal 8?

These tags serve to identify the type of query it is, which in turn allows alter hooks to determine if they need to take action. Tags should be an alphanumeric lowercase string, following the same rules as a PHP variable. (That is, letters, numbers, and underscores only and must begin with a letter.)

What is Entity query in Drupal 8?

entityQuery allows developers to query Drupal entities and fields in a SQL-like way. A Drupal site's tables and fields are never a 1-to-1 match for the site's entities and fields - entityQuery allows us to query the database as if they were 1-to-1.


1 Answers

As mentioned in the documentation you can query data by injecting Drupal's database connection class. For example:

use Drupal\Core\Database\Connection;

class DatabaseQueryExample {

  protected $connection;

  public function __construct(Connection $connection) {
    $this->connection = $connection;
  }

  public function queryExamples() {
    // db_query()
    $this->connection->query(" ... ");
    // db_select()
    $this->connection->select(" ... ");   
  }

}
like image 143
baikho Avatar answered Oct 12 '22 10:10

baikho