在激活钩子上的数据库中创建两个表

时间:2019-03-06 作者:Afzal Khan

我一直试图在激活挂钩上的数据库中生成两个表。但它只在激活挂钩上生成第一个表。我的代码做错了什么?

class Datetimepicker_Tables{

function __construct(){
    add_action(\'init\',array($this,\'create_tables\'));

}

function activate(){
    $this->create_tables();
    flush_rewrite_rules();
}

function create_tables(){
        global $wpdb;

        $date_table_name = $wpdb->prefix . \'booking_dates\';
        $time_table_name = $wpdb->prefix . \'booking_timeslots\';
        $charset_collate = $wpdb->get_charset_collate();

        $date_table = "CREATE TABLE $date_table_name (
            `id` int(11) NOT NULL AUTO_INCREMENT,
             `year` int(11) NOT NULL,
             `month` int(11) NOT NULL,
             `day` int(11) NOT NULL,
             PRIMARY KEY (`id`)
            ) $charset_collate;";

        $time_table = "CREATE TABLE $time_table_name (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `bid` int(11) NOT NULL,
            `time` int(11) NOT NULL,
            PRIMARY KEY (`id`),
            KEY `bid` (`bid`),
            CONSTRAINT `booking_timeslots_ibfk_1` FOREIGN KEY (`bid`) REFERENCES `booking_dates` (`id`)
            )  $charset_collate;";  

            require_once( ABSPATH . \'wp-admin/includes/upgrade.php\' );
            dbDelta( $date_table );
            dbDelta( $time_table );
}
}

$tablesclass = new Datetimepicker_Tables();
register_activation_hook(__FILE__,array($tablesclass,\'activate\'));

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

您在中没有使用正确的表名CONSTRAINT 条款:

CONSTRAINT `booking_timeslots_ibfk_1` FOREIGN KEY (`bid`) REFERENCES `booking_dates` (`id`)
这应该是:

CONSTRAINT `booking_timeslots_ibfk_1` FOREIGN KEY (`bid`) REFERENCES `$date_table_name` (`id`)
在哪里$date_table_name (如我所见)是正确的表名。

相关推荐