我已经有了一个表名table_one.
,现在我想再添加两个列。到目前为止一切正常。但是在我的方法中,我想检查表中是否存在像dropIfExists('table').
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('table_one', function (Blueprint $table) {
$table->string('column_one')->nullable();
$table->string('column_two')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('table_one', function (Blueprint $table) {
// in here i want to check column_one and column_two exists or not
$table->dropColumn('column_one');
$table->dropColumn('column_two');
});
}
答案 0 :(得分:5)
您需要像这样的东西
public function down()
{
if (Schema::hasColumn('users', 'phone'))
{
Schema::table('users', function (Blueprint $table)
{
$table->dropColumn('phone');
});
}
}
答案 1 :(得分:1)
您可以创建自己的“dropColumnIfExists()”函数来检查列是否存在,然后将其删除:
function myDropColumnIfExists($myTable, $column)
{
if (Schema::hasColumn($myTable, $column)) //check the column
{
Schema::table($myTable, function (Blueprint $table)
{
$table->dropColumn($column); //drop it
});
}
}
并在“down()”函数上使用它,如下所示:
public function down()
{
myDropColumnIfExists('table_one', 'column_two');
myDropColumnIfExists('table_one', 'column_one');
}
答案 2 :(得分:0)
只需将架构分为两个调用
public function up()
{
Schema::table('table_one', function (Blueprint $table) {
$table->dropColumn(['column_one', 'column_two']);
});
Schema::table('table_one', function (Blueprint $table) {
$table->string('column_one')->nullable();
$table->string('column_two')->nullable();
});
}