php - MySQL错误 "Foreign key constraint is incorrectly formed"

标签 php mysql sql laravel

我无法解决这个问题,我有这个创建语句:

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;

但是我收到错误:

外键约束格式不正确

有人可以建议我在这里做错了什么吗?

仅供引用,我正在使用 MySQL。

实际语句是使用 Laravel 迁移运行的,会出现错误:

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

最佳答案

我快速浏览了一下,发现了这个问题,它很好地解释了为什么会发生此错误:mysql Foreign key constraint is incorrectly formed error

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

关于php - MySQL错误 "Foreign key constraint is incorrectly formed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34262780/

相关文章:

mysql - 将 mysql 查询应用于数据库中的每个表

php - 如何向所选用户的浏览器发送通知

php - 如果该列中已存在数据,则 MySQL 将数据从一列移动到另一列

php - 我如何获取、查看和更新​​存储在数据库中的复选框值

javascript - 在javascript中获取输入文本的id值

jquery - 使用带有 mysql 查询的 Handlbars JS 填充多张卡片,但只有 1 个按钮有效

sql - SQL Server 将空值插入非空列时如何设置默认值?

sql - 如何在oracle的单个语句中添加带有外键约束的新列

sql - 如何选择至少一个 json 元素符合某些条件的 postgres 行?

php - 如何操作/访问从自动完成 ajax 收到的 json?