如何解决“无法添加外键约束”错误(字符串列)

时间:2019-04-04 17:24:48

标签: php database laravel eloquent database-migration

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

你能帮我吗?我尝试使用Google进行搜索,但并没有真正解决它的问题。

2 个答案:

答案 0 :(得分:0)

在您的第一次迁移中:

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

与主键和外键相同的列。可能是个问题。尝试删除主键。如果您确实需要将此键设为唯一键,则可以将其设为唯一键。

答案 1 :(得分:0)

The referenced column must have an index:

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();
});