首页 > 解决方案 > 如何修复“无法添加外键约束”错误(字符串列)

问题描述

我需要在两个表之间创建外键。类似于此 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');
        });
    }

你能帮助我吗?我试图用谷歌搜索,但没有什么能真正为我解决这个问题。

标签: phpdatabaselaraveleloquentdatabase-migration

解决方案


在您的第一次迁移中:

$table->primary('atribut');
$table->foreign('atribut')->references('atribut')->on('polozka_sabl');

与主键和外键相同的列。这可能是个问题。尝试删除主键。如果你真的需要它是唯一的,那么你可以让它成为唯一的键。


推荐阅读