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 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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