laravel errno 150 foreign key constraint is incorrectly formed

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

Can anybody help me to solve this problem?

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();         }); 

Error after running migration:

[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") 

回答1:

In case of foreign keys, the referenced and referencing fields must have exactly the same data type.

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.

You need to either add the unsigned clause to the id field definitions, or remove the unsigned clause from the foreign key fields.



回答2:

  • users
  • cashier refers users
  • student refers cashier

In addition when declaring foreign keys in laravel all tables your are referring must be on the top. In this case you can use "->unsigned()" modifier..



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!