我在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创建表(如果不存在)?
尝试这个
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();
}
}
要创建一个新表,只能通过Laravel Schema函数进行一次检查hasTable
。
但是,如果要在检查任何表之前删除任何表,则Schema具有一个称为的函数dropIfExists
。
Schema::dropIfExists('table_name');
如果存在表,它将删除表。
DB::transaction(function () {
// Create your table here with schema builder.
});
如果在事务关闭中引发异常,则事务将自动回滚。因此,尝试创建一个已经存在的表将引发错误。大多数数据库事务在Laravel中都应具有此关闭功能。
本文地址:http://php.askforanswer.com/moshishengchengqiruguobucunzaizechuangjianbiao.html
文章标签:laravel-5.1 , laravel-5.2 , php
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
文章标签:laravel-5.1 , laravel-5.2 , php
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!