doudi1750 2015-08-17 14:15
浏览 300

Laravel mysql即时创建表

I was trying to dynamicly create a database and then create table in that database

// Create DB
DB::connection('mysql-group')->statement(
    'CREATE DATABASE IF NOT EXISTS `' . $new_db_name . '`'
);

// Change DB
Config::set($prefix . '.database', $new_db_name);
DB::connection('mysql-group')->setDatabaseName($new_db_name);
DB::connection('mysql-group')->reconnect();

Log::debug(DB::connection('mysql-group')->getDatabaseName());

// Create Table
$table_schema = file_get_contents(base_path('resources/table_schema.sql'));
$split = explode("# --
", $table_schema);

foreach( $split as $sth ) {
    DB::connection('mysql-group')->select(DB::raw($sth));
}

The file table_schema.sql look like

CREATE TABLE IF NOT EXISTS `table`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `eid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `eid` (`eid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# --
CREATE TABLE IF NOT EXISTS `table2`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `eid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `eid` (`eid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# --

But the problem is, the error kept comming out:

SQLSTATE[HY000]: General error: 2053 (SQL: CREATE TABLE IF NOT EXISTS `table`  (`id` int(11) NOT NULL AUTO_INCREMENT, `eid` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `eid` (`eid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8; )

I tried adding this in the front, but the result is same

DB::connection('mysql-group')->statement(
    'SET SESSION wait_timeout=65535'
);

Any suggestion?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题
    • ¥15 请完成下列相关问题!
    • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
    • ¥15 求daily translation(DT)偏差订正方法的代码
    • ¥15 js调用html页面需要隐藏某个按钮