簡體   English   中英

SQLSTATE[HY000]:一般錯誤:1215 無法添加外鍵約束 [Laravel 7.0]

[英]SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint [Laravel 7.0]

嗨,當我嘗試在 laravel 上遷移我的遷移時,我繼續收到此錯誤,我已經嘗試了我在網上看到的所有建議,

錯誤是這個 SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table settoris add constraint settoris_stock_code_foreign foreign key ( stock_code ) references prodottis ( codice_stock ))

我得到了這個遷移,我不知道我做錯了什么我正在使用 laravel 7 和 php 7.4

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

class CreateProdottisTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('prodottis', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('codice_prodotto');
        $table->unsignedBigInteger('codice_stock');
        $table->date('data_di_scadenza');
        $table->decimal('costo', 10, 2);
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('prodottis');
}
}

和這個

<?php

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

class CreateSettorisTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('settoris', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->id();
        $table->unsignedBigInteger('stock_code');
        $table->string('settore');
        $table->string('scaffale');
        $table->integer('quantita_rimanente');
        $table->timestamps();
    });
    schema::table('settoris', function($table){
        $table->foreign('stock_code')->references('codice_stock')->on('prodottis');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('settoris');
}
}

您正在將外鍵設置為引用非primary鍵的codice_stock列。 您可以將其primary index ,如下所示:

$table->unsignedBigInteger('codice_stock')->primary();

有了這個,你會得到另一個錯誤。 那是因為你只能有一個主鍵。 所以你可以從prodottis表中刪除id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM