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?
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.
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. }
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.)
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.
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(" ... ");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With