laravel errno 150外键约束形成不正确 [英] laravel errno 150 foreign key constraint is incorrectly formed

查看:99
本文介绍了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();
        });

运行迁移后出现错误:

[Illuminate\Database\QueryException]
  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字段.但是,您将两个外键都创建为 unsigned 整数,因此,键的创建失败.

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.

您需要在id字段定义中添加unsigned子句,或从外键字段中删除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外键约束形成不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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