① 過程 :
我的環境 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 協議》,轉載必須註明作者和本文連結