Laravel迁移,检查有列,但得到列存在MySQL错误


Laravel Migration, checking hasColumn but getting Column Exists MySQL Error

我正在尝试创建一个迁移,向现有表添加一列。

为表执行初始创建的 up(( 方法如下所示:

public function up()
    {
        Schema::create('lead_assignments', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('version');
            $table->integer('reactor_track_id')->unsigned();
            $table->integer('lead_id')->unsigned();
            $table->integer('agent_id')->unsigned();
            $table->integer('lead_stage_id')->unsigned();
            $table->integer('managed_by_id')->unsigned();
            $table->integer('side_of_deal_id')->unsigned();
            $table->integer('coordinator_id')->unsigned();
            $table->decimal('referral_fee', 15, 2);
            $table->timestamp('response_ts');
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('lead_id')->references('id')->on('leads');
            $table->foreign('agent_id')->references('id')->on('agents');
            $table->foreign('lead_stage_id')->references('id')->on('lead_stages');
            $table->foreign('managed_by_id')->references('id')->on('managed_bys');
            $table->foreign('side_of_deal_id')->references('id')->on('side_of_deal');
            $table->foreign('coordinator_id')->references('id')->on('users');
        });
    }

我的 Alter up(( 方法看起来像这样:

   public function up()
    {
        Schema::table('lead_assignments', function (Blueprint $table) {
            if (!Schema::hasColumn('lead_assignments', 'property_type_id')) {
                $table->integer('property_type_id')->unsigned();
                $table->foreign('property_type_id')
                    ->references('id')
                    ->on('property_types');
            }
            if (!Schema::hasColumn('lead_assignments', 'referral_fee_expiration')) {
                $table->date('referral_fee_expiration')->nullable();
            }
           $table->dropForeign('lead_assignments_side_of_deal_id_foreign');
        });
        Schema::table('lead_assignments', function (Blueprint $table) {
            $table->integer('side_of_deal_id')->nullable()->change();
        });
    }

在这里,我尝试添加property_types列,首先检查它是否存在,然后在创建后使其成为外键。 这工作正常。然后我检查referral_fee_expiration列是否存在,如果没有,我尝试创建它。

在运行"迁移安装"后进行初始迁移时,我收到此MySQL错误:

[PDOException]
SQLSTATE[42S21]:列已存在:1060 重复的列名 "referral_fee_expiration">

这个

表没有其他更改,我不确定为什么它会抱怨该列已经存在,当除了这个之外没有迁移将其放在那里时,我正在检查它在创建之前是否存在。

有什么建议吗?

注意:

这是从一个新的数据库开始的。我运行"php artisan migrate install",然后运行"php artisan migrate"来产生错误。

如果您尝试更早地运行迁移并且它因任何错误而中断,那么在这种情况下,导致错误的语句之前的语句已经执行。但是,由于迁移在完全完成之前返回错误,因此它将状态显示为未迁移或挂起。

当您尝试重新运行迁移时,它会为您提供重复列的错误,因为该语句在错误之前已执行并且该列已添加到表中 - 这可能是原因。

在这种情况下,即使回滚迁移,在引发错误之前已经执行的语句也不会回滚,因为迁移本身未注册状态为完成。

因此,您可能需要使用 phpMyAdmin 或任何此类工具检查 MYSQL 数据库,如果表中存在有问题的列,请手动删除该列并尝试再次运行迁移。

希望它能帮助您解决问题。