使用hook_schema()添加表

时间:2010-12-28 23:08:02

标签: drupal

我打算在hook_schema的帮助下添加一个表。我已经定义了模式,并在我的模块中调用它。但是,没有创建架构。我哪里错了。我在sample2.install文件中有以下代码

    function sample2_schema(){
    $schema['mytable1'] = array(
    'description' => t('My table description'),
    'fields' => array(
     'mycolumn1' => array(
      'description' => t('My unique identifier'),
      'type' => 'serial',
      'unsigned' => true,
      'not null' => true,
      ), 
     'myvarchar' => array(
       'description' => t('My varchar'),
       'type' => 'varchar',
       'length' => 32,
       'not null' => true,
      ),
      'mytimestamp' => array(
        'description' => t('My timestamp'),
        'type' => 'int',
        'not null' => true,
      ),
    ),
    'indexes' => array(
      'myvarchar' => array('myvarchar'),
    ),
    'primary key' => array('mycolumn1'),
    'unique keys' => array(
       'mycolumn1' => array('mycolumn1'),
    ),
    );

    return $schema;
    }
      function sample2_install(){
    drupal_install_schema('sample2');
       }
      function sample2_uninstall(){
    drupal_uninstall_schema('sample2');
        }

要调用它,我在sample2.module文件中使用以下代码。

        $record = (object) NULL;
    $record->myvarchar = 'blah';
    $record->mytimestamp = strtotime('now');
    drupal_write_record('mytable1',$record);

这不会创建任何表格。

3 个答案:

答案 0 :(得分:6)

如果在添加sample2_schema()sample2_install()函数之前已存在并启用了sample2模块,则需要将其卸载(不仅仅是禁用),然后再次安装/启用它。否则,Drupal将不会使用您的hook_install()。另一种解决方案是在hook_update_N()实现中安装架构。然后使用u pdate.phpdrush updatedb运行更新代码。

function sample2_update_6001() {
  drupal_install_schema('sample2');
}

答案 1 :(得分:1)

要将新表添加到现有模块数据库模式,您可以执行以下操作:

 /**
 * Add generic API transaction log table.
 */
function commerce_paydollar_update_7004(&$sandbox){
  // Get schema definition for this module
  $schema = commerce_paydollar_schema();
  // Create a selected table from the schema definition  
  db_create_table('commerce_paydollar_api_txn', $schema['commerce_paydollar_api_txn']);
  $sandbox['#finished'] = TRUE;
}

答案 2 :(得分:0)

请参阅另一个非常相似的问题Drupal 6 module install file not creating tables in database

在你的问题的第二部分,你谈到'调用'表。在尝试从模块向表中写入任何内容之前,我建议先连接到数据库并检查表是否已成功创建。

卸载/重新安装模块将调用安装文件中的架构创建。如果语法正确,则会创建表。

如果您发现您的表没有被创建并且您认为它是一个语法问题,我建议首先尝试添加一列,然后添加其余列,并最后添加索引来简化代码。您可以在每个步骤之间安装/卸载。