如何修复'无法添加外键约束'错误(字符串列)

问题描述 投票:0回答:2

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

我尝试添加'collat​​e'方法,但结果没有任何反应。仍然得到错误

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

你能帮助我吗?我试着谷歌,但没有真正修复它对我来说。

php database laravel eloquent database-migration
2个回答
0
投票

在您的第一次迁移中:

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

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


0
投票

引用的列必须具有索引:

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();
});
© www.soinside.com 2019 - 2024. All rights reserved.