PHP:Laravel无法添加外键约束

时间:2018-08-23 06:19:56

标签: php mysql laravel laravel-5

我有文件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 migration时,出现了此错误

[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的类似问题,但没有任何效果。什么原因造成的任何见解?谢谢。

3 个答案:

答案 0 :(得分:4)

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

$table->unsignedInteger('role_id');

答案 1 :(得分:1)

只需在unsigned上输入role_id。 更改

$table->integer('role_id');

进入

$table->integer('role_id')->unsigned();

这是因为外键是无符号整数。

答案 2 :(得分:0)

要管理foreign key关系,两个表必须具有相同的数据类型列,而父表列必须是primary keyindex column。在您的情况下,role_id列是整数,而在users表中,id列不是整数,这就是错误的原因。

因此,使这两列在datatype方面相同,然后重试。

相关问题