代码之家  ›  专栏  ›  技术社区  ›  Md.Sukel Ali

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

  •  1
  • Md.Sukel Ali  · 技术社区  · 7 年前

    我已经有了一个表名 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');
        });
    }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Ismoil Shifoev    7 年前

    你需要这样的东西

      public function down()
        {
            if (Schema::hasColumn('users', 'phone'))
            {
                Schema::table('users', function (Blueprint $table)
                {
                    $table->dropColumn('phone');
                });
            }
        }
    
        2
  •  0
  •   PHP_only    7 年前

    把模式分成两个调用

    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();
        });
    }
    
    推荐文章