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



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

错误是这样的SQLSTATE[HY000]:一般错误:1215无法添加外键约束(SQL:更改表settoris添加约束settoris_stock_code_foreign外键(stock_code(引用prodottis(codice_stock((

我进行了迁移,我不知道我做错了什么——我使用的是laravel 7和php7.4

use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
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 IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
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

最新更新