怎样用laravel动态创建数据库表

新手上路,请多包涵

读取excel的数据后,想要填充到一张数据表里边。可是这张表不可能提前创建好。怎么使用laravel创建数据表,就像pdo::exec(create table example(...))这样。谢谢啦

阅读 9.4k
2 个回答

在自己正在写的项目中随便改动了一下用于测试

// 测试用路由
Route::group([], function() {
    Route::get('/test', function() {

        if(!Schema::hasTable('test')){
            Schema::create('test', function ($table) {
                $table->increments('id');
                $table->string('name'); 
            });
        }

        DB::table('test')->insert(['name'=>'123']);

        return 233;
    });
});

之后访问/test,便会检测是否有test数据库,并插入数据。不知道是否符合你的要求

参考资料
Laravel速查表#Schema
Laravel速查表#DB

推荐问题