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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54176290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:15:12  来源:igfitidea点击:

Check If a Column Exists in Laravel Migration File

phpsqllaravel

提问by Md.Sukel Ali

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').

我已经有了一个表名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');
    });
}

回答by Ismoil Shifoev

You need something just like this

你需要这样的东西

  public function down()
    {
        if (Schema::hasColumn('users', 'phone'))
        {
            Schema::table('users', function (Blueprint $table)
            {
                $table->dropColumn('phone');
            });
        }
    }

回答by PHP_only

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