安装自定义Drupal模块时数据库表未创建的排查求助
问题
我为自定义Drupal模块(mfa)编写了mfa.install文件,模块能无报错安装,但fp_attributes和fingerprints两张新表并未添加到数据库中。调试期间已多次卸载重装模块,且确认不需要使用hook_update_N()函数。以下是mfa.install文件的内容:
<?php // $Id$ use Drupal\Core\Database\Database; use Drupal\mfa\Constants; function mfa_schema() { $schema['fp_attributes'] = [ 'description' => 'Stores fingerprint attribute names and values for users.', 'fields' => [ 'attribute_seq' => [ 'description' => 'The identifier of the attribute.', 'type' => 'serial', 'unsigned' => true, 'not null' => true, ], 'attribute_name' => [ 'description' => 'The name of the attribute.', 'type' => 'varchar_ascii', 'length' => 255, 'not null' => true, ], 'attribute_value' => [ 'description' => 'The value of the attribute.', 'type' => 'varchar_ascii', 'length' => 255, 'not null' => true, ], ], 'primary key' => [ 'attribute_seq', ], // For documentation purposes only; foreign keys are not created in the database. 'foreign keys' => [ 'data_user' => [ 'table' => 'users', 'columns' => [ 'uid' => 'uid', ], ], ], ]; $schema['fingerprints'] = [ 'description' => 'Stores fingerprint attribute_seq values for users.', 'fields' => [ 'fingerprint_seq' => [ 'description' => 'The identifier for the fingerprint.', 'type' => 'serial', 'unsigned' => true, 'not null' => true, ], 'uid' => [ 'description' => 'The {users}.uid this record affects.', 'type' => 'int', 'unsigned' => true, 'not null' => true, ], ], 'primary key' => [ 'fingerprint_seq', ], // For documentation purposes only; foreign keys are not created in the database. 'foreign keys' => [ 'data_user' => [ 'table' => 'users', 'columns' => [ 'uid' => 'uid', ], ], ], ]; $attr_seqs = []; for ($i = 1; $i <= Constants::N_FP_ATTRIBUTES; $i++) $attr_seqs["attr_{$i}_seq"] = [ 'description' => "The attribute_seq value of the {$i}-th fingerprint attribute.", 'type' => 'int', 'unsigned' => true, 'not null' => false, ]; $schema['fingerprints']['fields'] += $attr_seqs; return $schema; }
检查Drupal日志无错误,通过MySQL命令行执行show tables;也找不到这两张表,请问原因是什么?
排查与解决方案
- 常量类加载失败:代码依赖
Constants::N_FP_ATTRIBUTES,如果这个类未正确加载(文件路径错误、命名空间不匹配、类未定义),会导致mfa_schema()函数终止执行,但错误可能被Drupal的错误抑制机制隐藏。可以先注释掉循环添加字段的代码段,直接返回包含两张表的$schema,测试能否创建表。如果注释后表成功创建,需检查Constants类:确保文件位于modules/custom/mfa/src/Constants.php,命名空间为Drupal\mfa,且类中存在N_FP_ATTRIBUTES常量定义。 - Schema缓存未清理:Drupal会缓存schema定义,修改
.install文件后旧缓存可能仍在生效。执行drush cache-rebuild(或后台手动清理所有缓存),再卸载重装模块,确保新的schema被读取并执行。 - 模块配置异常:确认
mfa.info.yml文件存在且配置正确,必填字段如name、type: module、core_version_requirement(匹配当前Drupal版本)需正确填写。同时检查模块目录权限,确保Drupal能正常读取,避免模块看似启用但实际未执行安装逻辑。 - 数据库前缀问题:如果Drupal配置了数据库前缀,表名会自动添加前缀(比如
mfp_fp_attributes)。执行show tables;时需查找带前缀的表,而非原始表名。 - 函数未被调用:可以在
mfa_schema()函数开头添加日志输出,比如\Drupal::logger('mfa')->notice('mfa_schema executed');,然后查看日志确认函数是否被触发。如果没看到这条日志,说明函数根本没被执行,需要检查模块的安装流程是否正常。
内容的提问来源于stack exchange,提问作者user4202824
相关产品推荐
相关产品推荐

