SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 [Laravel 7.0]
Posted
技术标签:
【中文标题】SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 [Laravel 7.0]【英文标题】:SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint [Laravel 7.0] 【发布时间】:2021-07-03 04:08:47 【问题描述】:您好,当我尝试在 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');
【问题讨论】:
必须在references
$table->foreign('stock_code')->references('codice_stock')->on('prodottis');
中定义主键列
您需要在settoris
表之前迁移prodottis
表。
@Shahrukh 我已经做到了,
@EsTeAa 它在 settoris 之前迁移产品
【参考方案1】:
您正在将外键设置为引用不是 primary
键的 codice_stock
列。你可以这样primary index
:
$table->unsignedBigInteger('codice_stock')->primary();
这样你会得到另一个错误!那是因为你只能有一个主键。所以你可以从prodottis
表中删除id
。
【讨论】:
以上是关于SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 [Laravel 7.0]的主要内容,如果未能解决你的问题,请参考以下文章
SQLSTATE[HY000]:一般错误:1215 无法在表用户中添加外键约束 Laravel
Laravel 5.0 [PDOException] SQLSTATE[HY000]:一般错误:1215 无法添加外键约束
SQLSTATE [HY000]:一般错误:1364 字段“名称”没有默认值