php - 如何修复“无法添加外键约束”错误(字符串列)
问题描述
我需要在两个表之间创建外键。类似于此 SQL 查询:
`alter table `katalog` add constraint `katalog_atribut_foreign`
foreign key (`atribut`) references `polozka_sabl` (`atribut`)`
我不断收到的错误:
Illuminate\Database\QueryException : 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');
与主键和外键相同的列。这可能是个问题。尝试删除主键。如果你真的需要它是唯一的,那么你可以让它成为唯一的键。
推荐阅读
- java-native-interface - 为什么使用 System.loadLibrary() 似乎不适用于 jshell 命令提示符?
- firebase - 如何阻止某些 IP 地址访问您在 Firebase 托管上的网站
- c - 我无法在我的 Windows 桌面上编译 GMP 库(用于 c 或 c++)
- dataframe - 如何使来自 for 循环的数组在 Julia 中全局可用?
- python - 训练准确度分数不同于后续测试准确度分数
- r - 如何表示组中的两个最高观察值(有两个条件)?
- r - confint() 是否以对数赔率或赔率返回 CI?
- wordpress - 用另一个替换 WordPress 主题的搜索栏
- python - 如何获取用户输入并将其替换为求解方法?
- sql - 逗号分隔字段上的表值函数 (TVF)