migrate:rollback 时 dropForeign 抛出的异常解决方案

① 过程 :

我的环境 Window 10 x64 & Homestead 8 & Laravel 6.x

 php artisan make:migration test_drop_foreigns
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class TestDropForeigns extends Migration
{
    /**
     * Run the migrations.
     *
     * [@return](https://learnku.com/users/31554) void
     */
    public function up()
    {
        Schema::create('test_a', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('b_id')->unsigned()->nullable()->index();//table b id index
            $table->timestamps();
        });

        Schema::create('test_b', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title')->nullable();
            $table->timestamps();
        });

        Schema::table('test_a', function ($table) {
            $table->foreign('b_id')->references('id')->on('test_b');
        });
    }

    /**
     * Reverse the migrations.
     *
     * [@return](https://learnku.com/users/31554) void
     */
    public function down()
    {
        Schema::table('test_a', function ($table) {
            $table->dropForeign('b_id');
        });
    }
}
php artisan migrate
php artisan migrate:rollback

你可以得到以下错误

Rolling back: 2019_12_14_023746_test_drop_foreigns
Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'b_id'; check that column/key exists (SQL: alter table `test_a` drop foreign key `b_id`)

② 怎么解决

讲以下代码

$table->dropForeign('b_id');

改成

···
$table->dropForeign(['b_id']);
···

清空数据库后重新执行执行

php artisan migrate
php artisan migrate:rollback

错误没有了!

③ 复数 dropForeign

$table->dropForeign(['b_id']);
$table->dropForeign(['c_id']);
$table->dropForeign(['d_id']);
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!