MySQL错误“;外键约束的形式不正确”;


MySQL error "Foreign key constraint is incorrectly formed"

我很难解决这个问题,我有一个创建语句:

create table `roles` 
(
    `name` varchar(255) not null,
    `description` varchar(255) not null, 
    `created_at` timestamp default 0 not null, 
    `updated_at` timestamp default 0 not null
) default character set utf8 collate utf8_unicode_ci;

但我得到了错误:

Foreign key constraint is incorrectly formed

有人能指出我在这里做错了什么吗?

仅供参考,我正在使用MySQL。

实际语句是使用Laravel迁移运行的,这会产生错误:

public function up()
{
    Schema::create('roles', function(Blueprint $table)
    {
        $table->string('name')->unique()->primary();
        $table->string('description');
        $table->timestamps();
    });
}

我快速浏览了一下,发现了这个SO问题,它很好地解释了为什么会出现这个错误:mysql外键约束格式错误

这对你来说意味着什么?这意味着您在某个地方有一个外键字段,期望使用角色表中的主键填充,但两者之间的类型不同。我可以想象,在另一个表的某个地方,你有一个列,比如role_id,它是int、bigint、tinyint等。不管怎样,你都不应该使用字符串作为主键。