1) 首次安装、启用模块时,填充新数据库表的最佳位置在哪里?我需要从外部源获取一些数据,并希望在用户安装/启用我的自定义模块时透明地执行此操作。
我在 {mymodule}_schema() 中创建模式,执行 drupal_install_schema({tablename});在钩子(Hook)安装中。然后我尝试使用 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)安装:
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 );
}
}
有人可以告诉我我错过了什么吗?
最佳答案
如果 ncbi_subsites_get_subsites() 不在 .install 文件中,则需要将其包含在模块中的任何文件。否则,它不会返回任何内容,在这种情况下,请尝试转储 $subsites 并退出。
关于drupal - 请解释 Drupal 模式和 drupal_write_record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2683422/