首页 > 解决方案 > PHP:Laravel 无法添加外键约束

问题描述

我有文件 2018_08_23_042408_create_roles_table.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateRolesTable extends Migration
{
public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('role_name');
        $table->string('description');
        $table->timestamps();
    });
}
public function down()
{
    Schema::drop('roles');
}
}

和 2018_08_23_042521_create_users_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('fullname');
        $table->string('email')->unique();
        $table->string('username')->unique();
        $table->string('password');
        $table->string('avatar_link');
        $table->integer('role_id');
        $table->foreign('role_id')->references('id')->on('roles');
        $table->rememberToken();
        $table->timestamps();
    });
}

public function down()
{
    Schema::table('role_user', function (Blueprint $table) {
        $table->dropForeign(['role_id']);
    });
    Schema::drop('users');
}
}

然而,当我运行 php artisan migrate 时,我得到了这个错误

[Illuminate\Database\QueryException]                                         
 SQLSTATE[HY000]: General error: 1215 Cannot add foreign key 
 constraint (SQL  
: alter table `users` add constraint `users_role_id_foreign` foreign 
key (`role_id`) references `roles` (`id`))                                                                                                             

[PDOException]                                                          
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint 

当我运行 php artisan:reset 时,它总是显示像“基表存在”这样的错误,我必须运行 php artisan tinker 和 Schema::drop('users') 来解决这个问题。我在stackoverflow上读过类似的问题,但没有任何效果。对造成这种情况的原因有任何了解吗?谢谢你。

标签: phpmysqllaravellaravel-5

解决方案


您必须将 unsignedInteger 用于 role_id,因为它在您的数据库中是 unsinged int (您使用增量)。然后尝试迁移。

$table->unsignedInteger('role_id');

推荐阅读