laravel errno 150 foreign key constraint is incorrectly formed(laravel errno 150 外键约束的格式不正确)
问题描述
谁能帮我解决这个问题?
Can anybody help me to solve this problem?
有 3 个表,有 2 个外键:
There are 3 tables with 2 foreign keys:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('firms', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->integer('firm_id')->unsigned()->nullable();
$table->foreign('firm_id')->references('id')->on('firms');
$table->timestamps();
});
运行迁移后出错:
[IlluminateDatabaseQueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter ta
ble `firms` add constraint `firms_user_id_foreign` foreign key (`user_id`)
references `users` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table `job`.`#sql-5fc_a1`
(errno: 150 "Foreign key constraint is incorrectly formed")
推荐答案
如果是外键,引用字段和引用字段的数据类型必须完全相同.
In case of foreign keys, the referenced and referencing fields must have exactly the same data type.
您将users
和firms
中的id
字段创建为有符号 整数.但是,您将两个外键创建为无符号 整数,因此键的创建失败.
You create the id
fields in both users
and firms
as signed integers. However, you create both foreign keys as unsigned integers, therefore the creation of the keys fail.
您需要将 unsigned
子句添加到 id
字段定义中,或者从外键字段中删除 unsigned
子句.
You need to either add the unsigned
clause to the id
field definitions, or remove the unsigned
clause from the foreign key fields.
这篇关于laravel errno 150 外键约束的格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:laravel errno 150 外键约束的格式不正确
基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 使用 PDO 转义列名 2021-01-01