Php SQLSTATE[HY000]:一般错误:1215无法添加外键约束[Laravel 7.0]

Php SQLSTATE[HY000]:一般错误:1215无法添加外键约束[Laravel 7.0],php,sql,laravel,eloquent,Php,Sql,Laravel,Eloquent,嗨,当我尝试在laravel上迁移我的迁移时,我继续遇到这个错误我尝试了我在网上看到的每个建议 错误是此SQLSTATE[HY000]:一般错误:1215无法添加外键约束(SQL:alter tablesettorisadd constraintsettoris\u stock\u code\u foreign外键(stock\u code)引用prodottis(codice\u stock) 我得到了这个迁移,我不知道我做错了什么我使用的是Laravel7和PHP7.4 use Illumi

嗨,当我尝试在laravel上迁移我的迁移时,我继续遇到这个错误我尝试了我在网上看到的每个建议

错误是此SQLSTATE[HY000]:一般错误:1215无法添加外键约束(SQL:alter table
settoris
add constraint
settoris\u stock\u code\u foreign
外键(
stock\u code
)引用
prodottis
codice\u stock

我得到了这个迁移,我不知道我做错了什么我使用的是Laravel7和PHP7.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');
}
}

您正在将外键设置为引用非
主键的
codice\u stock
列。您可以将其设置为如下所示的
主索引

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

有了这个,你会得到另一个错误!这是因为您只能有一个主键。因此,您可以从
prodottis
表中删除
id

您必须在
引用中定义主键列
$table->foreign('stock_code')->references('codice_stock')->on('prodottis')
您需要迁移
prodottis
表,在
settoris
表之前。@Shahrukh我已经这样做了,@EsTeAa它在settoris之前迁移prodottis