Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 246 Vote(s) - 3.63 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create a query in Drupal 8

#1
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?
Reply

#2
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);
Reply

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

}
Reply

#4
`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();

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through