【问题标题】:Schema Builder : Create Table if not exists架构生成器:如果不存在则创建表
【发布时间】:2016-05-29 19:13:13
【问题描述】:

我在 Schema Builder 中使用以下代码来创建表。

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

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

如果不存在,有什么方法可以使用 Schema builder 创建表?

【问题讨论】:

  • 你还在使用 laravel 内置的迁移工具吗?
  • 是的,5.2.15 版本。
  • 然后你运行php artisan migrate ?如果文件运行成功,它应该将其存储在数据库中,这样它就不会再次运行该文件
  • 我正在使用php artisan migrate:refresh,下次它会尝试重新运行旧脚本。
  • 尝试不使用:refresh

标签: php laravel-5.1 laravel-5.2


【解决方案1】:

试试这个

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();
    }
}

【讨论】:

  • 你也可以在添加之前先做if (Schema::hasTable('tblCategory')) { return; }
  • hi is this line of code if (!Schema::hasTable('tblCategory')) { // 创建 tblCategory 表 } 如果表存在?对吗?
【解决方案2】:

Please check the answer here

要创建一个新表,只需通过 Laravel Schema 函数hasTable 进行一次检查。

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

Schema::dropIfExists('table_name');

如果表存在,它将删除该表。

【讨论】:

    【解决方案3】:
    DB::transaction(function () {
            // Create your table here with schema builder.
    });
    

    如果事务闭包中抛出异常,事务将自动回滚。所以试图创建一个已经存在的表会抛出一个错误。大多数数据库事务在 Laravel 中都应该有这个闭包。

    https://laravel.com/docs/5.6/database

    【讨论】:

      猜你喜欢
      • 2011-01-29
      • 2013-01-10
      • 1970-01-01
      • 2010-12-03
      • 2013-05-26
      • 2010-09-19
      • 1970-01-01
      • 2014-11-11
      相关资源
      最近更新 更多