把数据存储到数据库表中(2)

老葛的Drupal培训班 Think in Drupal

我们可以把这段sql语句放到我们模块的README.txt文件中,这样我们就省事了,但是想要安装这个模块的其他用户就麻烦了,他们需要手工的将数据库表添加到他们的数据库中。换种方式,我们知道,在你启用你的模块时,Drupal能帮你创建相应的数据库表;我们这里将利用Drupal的这一点。我们将创建一个特殊的文件;文件的名字将使用你的模块名,而后缀则使用.install,所以对于annotate.module,这个文件名应该为annotate.install。创建文件sites/all/modules/custom/annotate/annotate.install,并输入以下代码:

 
<?php
// $Id$
 
/**
 * Implementation of hook_install().
 */
function annotate_install() {
    // Use schema API to create database table.
    drupal_install_schema('annotate');
}
 
/**
 * Implementation of hook_uninstall().
 */
function annotate_uninstall() {
    // Use schema API to delete database table.
    drupal_uninstall_schema('annotate');
    // Delete our module's variable from the variables table.
    variable_delete('annotate_node_types');
}
 
/**
 * Implementation of hook_schema().
 */
function annotate_schema() {
    $schema['annotations'] = array(
        'description' => t('Stores node annotations that users write.'),
        'fields' => array(
            'nid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
                'description' => t('The {node}.nid to which the annotation                      applies.'),
            ),
            'uid' => array(
                'type' => 'int',
                'unsigned' => TRUE,
                'not null' => TRUE,
                'default' => 0,
                'description' => t('The {user}.uid of the user who created the                      annotation.')
            ),
            'note' => array(
                'description' => t('The text of the annotation.'),
                'type' => 'text',
                'not null' => TRUE,
                'size' => 'big'
            ),
            'created' => array(
                'description' => t('A Unix timestamp indicating when the annotation
                    was created.'),
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0
            ),
        ),
        'primary key' => array(
            'nid', 'uid'
        ),
    );
 
    return $schema;
}

Drupal版本: