You are here

Drupal 8 数据库查询 进阶

g089h515r806 的头像
Submitted by g089h515r806 on 星期五, 2019-11-15 08:52

作者:亚艾元技术部

对于Drupal8的数据库操作相关,根据需要,我们需要掌握,创建数据库表,数据库表的增删改查。Drupal8内置的动态查询。Entity Query。

   创建数据库表,参考例子,核心模块dblog的 install文件的

dblog_schema() {
  $schema['watchdog'] = array(
    'description' => 'Table that contains logs of all system events.',
    'fields' => array(
      'wid' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique watchdog event ID.',
      ),
      'uid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {users}.uid of the user who triggered the event.',
      ),

   对于初学者,可以以这个为起步。 要建立一个数据库表,需要给模块建立一个install文件,里面实现hook_schema这个钩子函数 ,这里的hook替换成模块的机读名字。

$schema['watchdog']这个定义了表名。

定义表的字段:

      'uid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {users}.uid of the user who triggered the event.',
      ),

 

fields里面包含的是字段, 字段里面是字段的属性。

Drupal对于字段类型做了一层封装, 从而兼容mysql, sqlserver, pg sql

数据库字段类型:

文本型: varchar, char, text

数字型:int, float, numeric, serail

blob:序列化的

 

最下面是主键、索引。Mysql会自动为主键建立索引。索引的目的是加快查询速度。

    'primary key' => ['wid'],
    'indexes' => [
      'type' => ['type'],
      'uid' => ['uid'],
      'severity' => ['severity'],
],

根据自己的需要作出调整。

 

开始的不需要掌握数据库表的升级,这个可以后续掌握。我们只需要前期把数据库表一次建好即可,如果有问题,可以卸载了模块,重新安装,作出调整。

 

建立了数据库表以后,使用以下的代码,向数据库插入数据:

向数据库插入记录

$sql = "INSERT INTO contactus (name,company_name,mail,phone) VALUES(:name,:company_name,:mail,:phone)";
       $result = db_query($sql, array(':name ' => $name, ':company_name ' => $company_name, ':mail' => $mail, ':phone ' => $phone));

注意,这里使用

:name

 ':name ' => $name

这种用法是为了防止数据库sql注入。

 

 

查询sql示例:

    $sql = “select * from contactus”;
       $result = db_query($sql, array(':mail' => $mail));
       //$record = $result->fetchObject();
       //$record = $result->fetch();
       //$record = $result->fetchAssoc();
 
       foreach($result as $key => $value){
         $output .= '<tr>';
         $output.= '<td>' . $value->id.'</td>' ;
         $output.= '<td>' . $value->name.'</td>' ;
      $output .= '</tr>';
}

  构建一个sql,使用db_query获取查询结果,循环,构建拼凑的输出字符串。

   默认每个取出来的结果是一个对象。

  $result->fetchObject();  //取得一个查询记录,以对象的形式返回。
  $result->fetch();   //取得一个对象,等价于fetchObject()
$result->fetchAssoc();  //取得一个查询记录,以数组的形式返回。

   

对于Drupal的数据库操作,掌握这些,就能够干活了。

 

Drupal里面的数据库表结构,特别是涉及到字段的时候,自己构建关联查询比较麻烦,让人头痛。Drupal对此作了封装,让对于Drupal实体的查询,看起来就像在一个表中进行,它在背后,帮助用户构建了复杂的sql。

   $query = \Drupal::entityQuery('node');
    $query->condition('status', 1);
    $query->condition('type', ‘article’);
    $entity_ids = $query->execute();
   $entitys = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);


论坛:

Drupal版本: