2017-12-31 43 views
1

이 악명 높은 오류가 발생하여 잘못 된 것이 무엇인지 알 수 없습니다.MySQL 1215 외래 키 제약 조건을 추가 할 수 없습니다 - Laravel 5

class CreateOrdersTable extends Migration 
{ 
    public function up() 
    { 
     Schema::create('orders', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->timestamps(); 

      $table->integer('customer_id')->unsigned(); 
      $table->integer('partner_id')->unsigned(); 

      $table->string('status', 20)->default(Order::getDefaultStatus()); 
      $table->string('paid', 20)->default('no'); 

      $table->decimal('visitation_charges', 20, 2)->default(0); 
      $table->decimal('taxes', 20, 2)->default(0); 
      $table->decimal('charges', 20, 2)->default(0); 
      $table->decimal('discount', 20, 2)->default(0); 
      $table->decimal('total', 20, 2)->default(0); 

      $table->foreign('customer_id')->references('id') 
        ->on('customers')->onDelete('cascade') 
        ->onUpdate('cascade'); 
      $table->foreign('partner_id')->references('id') 
        ->on('partners')->onDelete('cascade') 
        ->onUpdate('cascade'); 
     }); 
    } 

    public function down() 
    { 
     Schema::dropIfExists('orders'); 
    } 
} 

class CreatePaymentsTable extends Migration 
{ 
    public function up() 
    { 
     Schema::create('payments', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->timestamps(); 

      $table->integer('order_id')->unsigned(); 
      $table->string('gateway', 100); 
      $table->string('transaction_id', 100); 
      $table->decimal('amount', 20, 2); 
      $table->string('status', 20)->default(Payment::getDefaultStatus()); 
      $table->string('comments', 2000)->nullable(); 

      $table->foreign('order_id')->references('id') 
        ->on('orders')->onDelete('set null') 
        ->onUpdate('cascade'); 
     }); 
    } 

    public function down() 
    { 
     Schema::dropIfExists('payments'); 
    } 
} 

내가 오류입니다 : 내가 두 테이블 orderspayments 사이의 관계를 구축하기 위해 노력하고있어, 누구의 마이그레이션은 다음과 같이 정의된다 나는 또한 테이블 엔진 것을 확인했습니다

[Illuminate\Database\QueryException]                 
    SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `payments` add constraint `payments_order_id_foreign` foreign key (`order_id`) references `orders` (`id`) on delete set null on update cascade) 

, 내가 잘못거야

| orders | CREATE TABLE `orders` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `created_at` timestamp NULL DEFAULT NULL, 
    `updated_at` timestamp NULL DEFAULT NULL, 
    `customer_id` int(10) unsigned NOT NULL, 
    `partner_id` int(10) unsigned NOT NULL, 
    `status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'created', 
    `paid` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no', 
    `visitation_charges` decimal(20,2) NOT NULL DEFAULT '0.00', 
    `taxes` decimal(20,2) NOT NULL DEFAULT '0.00', 
    `charges` decimal(20,2) NOT NULL DEFAULT '0.00', 
    `discount` decimal(20,2) NOT NULL DEFAULT '0.00', 
    `total` decimal(20,2) NOT NULL DEFAULT '0.00', 
    PRIMARY KEY (`id`), 
    KEY `orders_customer_id_foreign` (`customer_id`), 
    KEY `orders_partner_id_foreign` (`partner_id`), 
    CONSTRAINT `orders_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, 
    CONSTRAINT `orders_partner_id_foreign` FOREIGN KEY (`partner_id`) REFERENCES `partners` (`id`) ON DELETE CASCADE ON UPDATE CASCADE 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci 

| payments | CREATE TABLE `payments` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `created_at` timestamp NULL DEFAULT NULL, 
    `updated_at` timestamp NULL DEFAULT NULL, 
    `order_id` int(10) unsigned NOT NULL, 
    `gateway` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, 
    `transaction_id` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, 
    `amount` decimal(20,2) NOT NULL, 
    `status` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pending', 
    `comments` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci 

확실하지 : 등 열 유형, 문자 집합은 동일합니다 (다음은 show create의 출력입니다) . :/

+0

'payments_id'가 'orders' 테이블에 존재하지 않는 레코드를 참조하는 레코드가있을 수 있습니까? 이것이 내가 확인할 첫 번째 것입니다. –

+0

결제 전에 주문 표가 생성 되었습니까? 또는 order_id가 주문 테이블에 존재하지 않는 지불 기록이있을 수 있습니다. –

+0

@TimBiegeleisen 이제 해결되었습니다. 댓글 주셔서 감사합니다. :-) – dotslash

답변

1

NOT NULL으로 선언 된 열은 외래 키 ON DELETE SET NULL을 만들 수 없습니다.

열은 NULL 일 수 없습니다.

  • 생략 ON DELETE SET NULL : 다음 중 하나를 수행 할 경우

    외부 키 작품

    alter table `payments` add constraint `payments_order_id_foreign` 
    foreign key (`order_id`) references `orders` (`id`) on update cascade; 
    
  • 을 허용하는 열을 수정 NULL :

    alter table payments modify order_id int(10) unsigned null; 
    
1

it 더 나은 다른 외부 키 마이그레이션 구축해야 오류가 여전히 주문 및 지불 테이블을 수동으로 삭제하고 제거해야합니다 존재하는 경우

php artisan make:migration add_foreign_key_to_payment_table --table=payments

그래서이 마이그레이션에 외래 키 지불을 추가를, 다음 php artisan migrate

을 실행 마이그레이션 테이블에서 이들을 다시 추가하십시오.

이 정보가 도움이되기를 바랍니다. 좋은 날! :)

1

(null) ()을 order_id 열에 추가하십시오. 아래처럼. 당신의 실수는 사라질 것입니다.

class CreatePaymentsTable extends Migration 
{ 
    public function up() 
    { 
     Schema::create('payments', function (Blueprint $table) { 
     // your others columns 
     $table->integer('order_id')->unsigned()->nullable(); 
    } 
}