php 如何在 Drupal 8 中创建查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33944735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:40:44  来源:igfitidea点击:

How to create a query in Drupal 8

phpmysqldrupaldrupal-8

提问by Mina Adel

I am used to using db_select in drupal 7 but now it's deprecated in drupal 8

我习惯于在 drupal 7 中使用 db_select 但现在它在 drupal 8 中已弃用

So, If I need to create a query to list all users from users_field_datatable, What should I do?

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

Do I still use db_selector db_queryeven though they are deprecated functions? Or create a new controller to extend from "Select class" and make my query?

我是否仍然使用db_selectdb_query即使它们是不推荐使用的功能?或者创建一个新的控制器来扩展“ Select class”并进行查询?

回答by Eyal

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

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

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


Using entity query & loadMultiple

使用实体查询和 loadMultiple

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

如果您需要更复杂的带有排序、范围、分页器和 OR/AND 条件组的查询,您应该使用实体查询

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

回答by baikho

As mentioned in the documentation you can query data by injecting Drupal's database connection class. For example:

如文档中所述,您可以通过注入 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(" ... ");   
  }

}

回答by Rijin

db_select,db_insert,db_update,etc were depricated in Drupal 8.0.x, 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);

db_select、db_insert、db_update 等在 Drupal 8.0.x 中被弃用,将在 Drupal 9.0.0 中删除。相反,从容器中获取一个注入到您的服务中的数据库连接,并在其上调用 select()。例如,$injected_database->select($table, $alias, $options);

eg:

例如:

$db = \Drupal::database();

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

$db->insert();

$db->update();