Php SQLSTATE[HY000]:一般错误:1215无法添加外键约束[Laravel 7.0]
嗨,当我尝试在laravel上迁移我的迁移时,我继续遇到这个错误我尝试了我在网上看到的每个建议 错误是此SQLSTATE[HY000]:一般错误:1215无法添加外键约束(SQL:alter tablePhp 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
settoris
add constraintsettoris\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