1)首次安装模块时,在哪里填充新数据库表的最佳位置?我需要从外部源获取一些数据,并希望在用户安装/启用我的自定义模块时透明地执行此操作。
我在{mymodule} _schema()中创建架构,执行drupal_install_schema({tablename});在hook_install中。然后我尝试使用drupal_write_record填充hook_enable中的表。
我确认表已创建,但是当hook_enable执行时我没有错误,但是当我查询新表时,我没有返回任何行 - 它是空的。
以下是我尝试过的代码的一种变体:
/**
* Implementation of hook_schema()
*/
function ncbi_subsites_schema() {
// we know it's MYSQL, so no need to check
$schema['ncbi_subsites_sites'] = array(
'description' => 'The base table for subsites',
'fields' => array(
'site_id' => array(
'description' => 'Primary id for site',
'type' => 'serial',
'unsigned' => TRUE,
'not null' => TRUE,
), // end site_id
'title' => array(
'description' => 'The title of the subsite',
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '',
), //end title field
'url' => array(
'description' => 'The URL of the subsite in Production',
'type' => 'varchar',
'length' => 255,
'default' => '',
), //end url field
), //end fields
'unique keys' => array(
'site_id'=> array('site_id'),
'title' => array('title'),
), //end unique keys
'primary_key' => array('site_id'),
); // end schema
return $schema;
}
这是hook_install:
function ncbi_subsites_install() {
drupal_install_schema('ncbi_subsites');
}
这是hook_enable:
function ncbi_subsites_enable() {
drupal_get_schema('ncbi_subsites_site');
// my helper function to get data for table (not shown)
$subsites = ncbi_subsites_get_subsites();
foreach( $subsites as $name=>$attrs ) {
$record = new stdClass();
$record->title = $name;
$record->url = $attrs['homepage'];
drupal_write_record( 'ncbi_subsites_sites', $record );
}
}
有人可以告诉我我错过了什么吗?
答案 0 :(得分:1)
如果ncbi_subsites_get_subsites()不在.install文件中,则需要在模块中包含其中的任何文件。否则,它什么都不返回,在这种情况下尝试转储$ subsites并退出。
答案 1 :(得分:1)
我认为答案是drupal_write_record不适用于安装或启用挂钩。我认为在启用或安装时,您必须编写SQL。这是我从阅读一些帖子中得到的印象,这些帖子提到架构在这些钩子中不可用。
答案 2 :(得分:1)
首先(假设Drupal 6),无法从hook_install()调用drupal_write_record()
,因为Drupal找不到从模块定义的数据库模式,该模块仍将安装并启用。
相反,您需要使用db_query()
功能。 (评论提到了一种通过将默认数据提供给hook_schema()
序列化来包含默认数据的方法,但我没有找到相关文档。)
但是,您是否正在使用(Drupal 7的开发版本),您想要查看db_insert()
函数。