laravel errno 150 外键约束的格式不正确

时间:2022-11-17
本文介绍了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.

您将usersfirms 中的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 外键约束的格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:Laravel 5.4 字段没有默认值 下一篇:在 Laravel 5 中扩展请求类

相关文章

最新文章