架构生成器:如果 Table 不存在则创建
Schema Builder : Create Table if not exists
我在 Schema Builder 中使用以下代码来创建 table。
Schema::create('tblCategory', function (Blueprint $table) {
$table->increments('CategoryID');
$table->string('Category', 40);
$table->unique('Category', 'tblCategory_UK_Category');
$table->timestamps();
});
这里的问题是,如果我必须创建新的 table,所有旧脚本都会运行并显示 table 已经存在的错误。
如果 table 不存在,是否可以使用模式生成器创建?
试试这个
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();
}
}
Please check the answer here
要创建一个新的 table,只有 Laravel 模式函数 hasTable
进行一次检查。
但是如果您想在检查任何 table 之前删除它,那么 Schema 有一个名为 dropIfExists
.
的函数
Schema::dropIfExists('table_name');
如果 table 存在,它会掉落 table。
DB::transaction(function () {
// Create your table here with schema builder.
});
如果事务Closure中抛出异常,事务会自动回滚。所以尝试创建一个已经存在的 table 会抛出错误。大多数数据库事务应该在 Laravel.
中有这个闭包
我在 Schema Builder 中使用以下代码来创建 table。
Schema::create('tblCategory', function (Blueprint $table) {
$table->increments('CategoryID');
$table->string('Category', 40);
$table->unique('Category', 'tblCategory_UK_Category');
$table->timestamps();
});
这里的问题是,如果我必须创建新的 table,所有旧脚本都会运行并显示 table 已经存在的错误。
如果 table 不存在,是否可以使用模式生成器创建?
试试这个
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();
}
}
Please check the answer here
要创建一个新的 table,只有 Laravel 模式函数 hasTable
进行一次检查。
但是如果您想在检查任何 table 之前删除它,那么 Schema 有一个名为 dropIfExists
.
Schema::dropIfExists('table_name');
如果 table 存在,它会掉落 table。
DB::transaction(function () {
// Create your table here with schema builder.
});
如果事务Closure中抛出异常,事务会自动回滚。所以尝试创建一个已经存在的 table 会抛出错误。大多数数据库事务应该在 Laravel.
中有这个闭包