12

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?

acrosman
  • 12,814
  • 10
  • 39
  • 55
Mina Atia
  • 780
  • 1
  • 4
  • 13
  • I would recommend you to rephrase the question probably to something like "how to make a query in D8" because as is it attracts votes to close due to being opinion-based. – Wtower Nov 27 '15 at 10:03
  • What are you trying to achieve? – Eyal Nov 28 '15 at 02:23

3 Answers3

20

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);
Eyal
  • 758
  • 6
  • 23
10

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(" ... ");   
  }

}
baikho
  • 5,203
  • 4
  • 40
  • 47
10

db_select, db_insert, db_update, etc... were deprecated in Drupal 8.0.x and will be removed in Drupal 9.0.0.

Instead get a database connection injected into your service from the container and call select() on it. 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();
baikho
  • 5,203
  • 4
  • 40
  • 47
Rijin
  • 625
  • 1
  • 4
  • 13
  • Question: areboth instances of `'t'` the name of the rows you want to get? – Chris Happy Aug 05 '17 at 23:27
  • 1
    fields() takes more than 1 parameter, if you use ->fields('t') i.e, you provide only 1 parameter, which is what you have defined as the alias, it translates to '*' that you would have used to fetch all fields in case you were writing an SQL query. to fetch a set of fields, say 'a', 'b' from the table you use ->fields('t', array('a', 'b')) – dresh Mar 10 '19 at 12:59