建立模块请参考 《Drupal 7 模块开发 建立》
如果你要支持中文,文件格式必须保存为 UTF-8,NO BOM
------------------------------
要为自己模块建立一个单独的表(table),需要用到 hook_schema
表名称:myform
function my_first_module_schema() {
$schema['myform'] = array(
'description' => '第一个表单',
'fields' => array(
'id' => array(
'type' => 'serial',
'unsigned' => true,
'not null' => true,
'description' => '自增主键'
),
'title' => array(
'type' => 'varchar',
'length' => 255,
'not null' => true,
'default' => '',
'description' => '标题',
),
'fullname' => array(
'type' => 'varchar',
'length' => 64,
'not null' => true,
'default' => '',
'description' => '姓名',
),
'email' => array(
'type' => 'varchar',
'length' => 255,
'not null' => true,
'default' => '',
'description' => '电子邮件',
),
'body' => array(
'type' => 'text',
'not null' => false,
'size' => 'big',
'serialize' => true,
'description' => '留言内容',
),
'timestamp' => array(
'type' => 'int',
'not null' => true,
'default' => 0,
'description' => '留言时间',
),
),
'indexes' => array(
'myform_timestamp' => array('timestamp'),
),
'primary key' => array('id'),
);
return $schema;
}
$schema 具体用法可以参考 Schema API
description 说明
字符串。纯文本格式。表(table)的说明
fields 字段
数组。说明数据库表的结构。array(‘fieldname‘ => specification),具体可以看文章下面的《详解fields》
primary key 主键
数组。可以表示一个或多个主关键字
'primary key' => array('id'),
unique keys 唯一键
数组。(‘键名‘ => specification)
foreign keys 外键
数组。(‘外键名‘ => specification)
specification 结构
array (
‘table‘ => ’外表名字‘,
’columns‘ => array(‘本表字段名‘ => ‘对应外表字段名‘)
)'foreign keys' => array( 'node_revision' => array( 'table' => 'node_revision', 'columns' => array('vid' => 'vid'), ), 'node_author' => array( 'table' => 'users', 'columns' => array('uid' => 'uid'), ), ),上面代码说明:
外键名是:node_revision 和 node_author node_author 把本表中uid 和 users表中的uid关联起来
indexes 索引
数组。(‘索引名‘ => specification)。
specification 结构: array(‘字段名1‘, ‘字段名2‘, .....) 可以一个或多个
'indexes' => array( 'myform_timestamp' => array('timestamp'), ),上面代码说明:把 timestamp 做索引,索引名为 myform_timestamp
详解 fields
| tiny | small | medium | normal | big | |
|---|---|---|---|---|---|
| varchar | VARCHAR | ||||
| char | CHAR | ||||
| text | TINYTEXT | TINYTEXT | MEDIUMTEXT | TEXT | LONGTEXT |
| serial | TINYINT | SMALLINT | MEDIUMINT | INT | BIGINT |
| int | TINYINT | SMALLINT | MEDIUMINT | INT | BIGINT |
| float | FLOAT | FLOAT | FLOAT | FLOAT | DOUBLE |
| numeric | DECIMAL | ||||
| blob | BLOB | LONGBLOB |
更多数据类型的定义,可以参考:Data types Drupal会根据连接不同数据库转换成相应的SQL
MySQL一些常用类型定义
'id' => array(
'type' => 'serial',
'unsigned' => true,
'not null' => true,
'description' => '自增主键'
),'timestamp' => array(
'type' => 'int',
'not null' => true,
'default' => 0,
'description' => '留言时间',
),
Drupal 7 模块开发 创建自定义表(table) (hook_schema)
原文:http://blog.csdn.net/stevenhzhang/article/details/39717811