我需要在两个表之间创建外键。与此 SQL 查询类比:
`alter table `katalog` add constraint `katalog_atribut_foreign`
foreign key (`atribut`) references `polozka_sabl` (`atribut`)`
我一直得到的错误:
IlluminateDatabaseQueryException : SQLSTATE[HY000]: General
error: 1215 Cannot add foreign key constraint (SQL: alter table
`katalog` add constraint `katalog_atribut_foreign` foreign key
(`atribut`) references `polozka_sabl` (`atribut`))
我试图添加"整理"方法,但结果没有任何反应。仍然收到错误
2019_04_02_230803_create_katalog.php:
public function up()
{
Schema::create('katalog', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->string('atribut')->collate('utf8_general_ci');
$table->string('popis');
$table->timestamps();
});
Schema::table('katalog', function($table) {
$table->primary('atribut');
$table->foreign('atribut')->references('atribut')->on('polozka_sabl');
});
}
2019_04_02_230754_create_polozka_sabl.php:
public function up()
{
Schema::create('polozka_sabl', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigInteger('idproj')->unsigned();
$table->string('atribut')->collate('utf8_general_ci');
$table->primary(['idproj', 'atribut']);
$table->timestamps();
});
Schema::table('polozka_sabl', function($table) {
$table->foreign('idproj')->references('idproj')->on('projekt');
});
}
你可以帮我吗?我试图谷歌,但没有什么真正为我解决它。
在第一次迁移中:
$table->primary('atribut');
$table->foreign('atribut')->references('atribut')->on('polozka_sabl');
与主键和外键相同的列。这可能是一个问题。尝试删除主键。如果你真的需要它是唯一的,那么你可以让它成为唯一的键。
引用的列必须具有索引:
Schema::create('polozka_sabl', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigInteger('idproj')->unsigned();
$table->string('atribut')->collate('utf8_general_ci')->index();
$table->primary(['idproj', 'atribut']); ^^^^^^^
$table->timestamps();
});