如何在Drupal 8中创建查询

Min*_*del 10 php mysql drupal drupal-8

我习惯在drupal 7中使用db_select,但现在它在drupal 8中被弃用了

所以,如果我需要创建一个查询来列出表中的所有用户users_field_data,我该怎么办?

我仍然使用db_select或者db_query即使它们被弃用了吗?或者创建一个新的控制器以从" Select class" 扩展并进行查询?

Eya*_*yal 17

取决于你想要达到的目标.


使用存储对象

如果要对用户进行简单查询,则应使用存储对象的loadByProperties

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

使用实体查询和loadMultiple

如果您需要使用排序,范围,寻呼机和OR/AND条件组进行更复杂的查询,则应使用实体查询

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


bai*_*kho 8

如文档中所述,您可以通过注入Drupal的数据库连接类来查询数据.例如:

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

}
Run Code Online (Sandbox Code Playgroud)


Rij*_*jin 8

在Drupal 8.0.x中对db_select,db_insert,db_update等进行了描述,将在Drupal 9.0.0中删除.相反,从容器中获取注入服务的数据库连接,并在其上调用select().例如,$ inject_database-> select($ table,$ alias,$ options);

例如:

$db = \Drupal::database();

$data = $db->select('table_name','t')->fields('t')->execute();

$db->insert();

$db->update();
Run Code Online (Sandbox Code Playgroud)