How to create a query in Drupal 8

I am using db_select in drupal 7, but now it is deprecated in drupal 8

So, if I need to create a query to list all users from the users_field_data table, what should I do?

Am I still using db_select or db_query , although they are deprecated functions? Or create a new controller for the extension from the " Select class " and make my request?

+7
php mysql drupal drupal-8
source share
3 answers

Depends on what you are trying to achieve.


Using storage object

If you want to make a simple query about users, then you should use the loadByProperties of the storage object

 $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties([ 'name' => 'bar' ]); 

Using entity query and loadMultiple

If you need a more complex query with sort, range, pager and OR / AND groups, you should use an object query

 $ids = \Drupal::entityQuery('user')->condition('name', 'foo')->execute(); $users = User::loadMultiple($ids); 
+12
source share

As mentioned in the documentation, you can request data by entering the Drupal 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(" ... "); } } 
+6
source share

db_select, db_insert, db_update, etc. have been deprived of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, you get the database connection entered into your service from the container and call select (). For example, $ injected_database-> select ($ table, $ alias, $ options);

eg:

 $db = \Drupal::database(); $data = $db->select('table_name','t')->fields('t')->execute(); $db->insert(); $db->update(); 
+6
source share

All Articles