duanbo6871
2019-01-14 05:47
浏览 61
已采纳

检查Laravel迁移文件中是否存在列

Already I have a table name table_one. Now I want to add two more columns to it. Everything works fine so far. But in my method, I want to check a column exists or not in my table like 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');
    });
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douzi2333 2019-01-14 05:53
    已采纳

    You need something just like this

      public function down()
        {
            if (Schema::hasColumn('users', 'phone'))
            {
                Schema::table('users', function (Blueprint $table)
                {
                    $table->dropColumn('phone');
                });
            }
        }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duangan6797 2019-01-14 06:07

    Just break the schema up into two calls

    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();
        });
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题