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

新手上路,请多包涵

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

原文由 Md.Sukel Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 579
2 个回答

你需要这样的东西

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

原文由 Ismoil Shifoev 发布,翻译遵循 CC BY-SA 4.0 许可协议

要动态检查您的表格列,您可以尝试以下操作:

 public function dropIfExists($table, $column)
{
    if (Schema::hasColumn($table, $column)) //check the column
    {
        Schema::table($table, function (Blueprint $table) use ($column)
        {
            $table->dropColumn($column); //drop it
        });
    }

}

原文由 tayeb320 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题