How to create a query in Drupal 8

Mina Adel picture Mina Adel · Nov 26, 2015 · Viewed 21.1k times · Source

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?

Answer

Eyal picture Eyal · Nov 28, 2015

Depends on what you are trying to achieve.


Using the storage object

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

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

Using entity query & loadMultiple

If you need a more complex query with sorts, range, pager and OR/AND condition groups you should use entity query

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