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 外键约束的格式不正确
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- PHP foreach() 与数组中的数组? 2022-01-01