架构构建器:如果不存在则创建表

Pan*_*kaj 27 php laravel-5.1 laravel-5.2

我在Schema Builder中使用下面的代码来创建表.

Schema::create('tblCategory', function (Blueprint $table) {
    $table->increments('CategoryID');
    $table->string('Category', 40);
    $table->unique('Category', 'tblCategory_UK_Category');
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

问题是,如果我必须创建新表,则所有旧脚本都会运行并显示该表已存在的错误.

有没有办法创建表,如果不存在使用架构生成器?

par*_*oid 51

试试这个

if (!Schema::hasTable('tblCategory')) {
     Schema::create('tblCategory', function($table){
            $table->engine = 'InnoDB';
            $table->increments('CategoryID');
            $table->string('Category', 40);
            $table->unique('Category', 'tblCategory_UK_Category');
            $table->timestamps();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你也可以做`if(Schema :: hasTable('tblCategory')){return; 在添加它之前. (6认同)

Brn*_*iya 6

请在这里查看答案

要创建一个新表,Laravel Schema函数只能进行一次检查hasTable.

但是如果你想在检查它存在之前删除任何表,那么Schema有一个叫做的函数dropIfExists.

Schema::dropIfExists('table_name');
Run Code Online (Sandbox Code Playgroud)

如果表存在,它将删除表.