常规错误:创建键约束时出现1005-Laravel [英] General error: 1005 when creating a key constraint - Laravel

查看:71
本文介绍了常规错误:创建键约束时出现1005-Laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Laravel中添加外键约束时,出现以下错误.

When trying to add a foreign key constraint in Laravel I am getting the following error.

[PDOException]                                                                                
SQLSTATE[HY000]: General error: 1005 Can't create table 'ts.#sql-5769_62' (errno: 150)

我有2个表,usersteams.关系是团队可以有许多用户,而用户只有一个团队.

I have 2 tables, users and teams. The relationship is teams can have many users and users have one team.

用户

$table->increments('id');
        $table->integer('team_id');

        $table->string('name', 255);
        $table->string('username', 32)->unique();
        $table->string('email', 320);
        $table->string('password', 64);

        $table->foreign('team_id')->references('id')->on('teams');


        $table->timestamps();

团队

        $table->increments('id');

        $table->string('team_name', 255);
        $table->string('website', 255);

        $table->timestamps();

我做错了什么?这也是我第一次使用迁移,因此欢迎您指出任何愚蠢的错误.

What am I doing wrong? Also this is my first time using migrations so any help in pointing out silly errors is welcomed.

推荐答案

尝试为team_id指定unsigned:

$table->integer('team_id')->unsigned();

主键$table->increments('id');是无符号整数,因此外键$table->integer('team_id');应该与它的类型匹配.

You primary key $table->increments('id'); is an unsigned integer, so the foreign key $table->integer('team_id'); should match it's type.

引自 Laravel文档:

注意:创建引用增量的外键时 整数,请记住始终使外键列为无符号.

Note: When creating a foreign key that references an incrementing integer, remember to always make the foreign key column unsigned.

更新

还要确保首先创建team表,因此架构"构建器不要尝试在不存在的表上创建外键.

Update

Also make sure you create the team table first, so the Schema builder don't attempt to create a foreign key on a non existing table.

这篇关于常规错误:创建键约束时出现1005-Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆