php:laravel不能添加外键约束

b1zrtrql  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(259)

我有文件2018\u 08\u 23\u 042408\u create\u roles\u 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\u 08\u 23\u 042521\u create\u users\u 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 it 总是显示错误,比如“基表存在”,我必须运行php artisan tinker和schema::drop('users')来修复这个错误。我在stackoverflow上也读过类似的问题,但都没用。你知道这是什么原因吗?谢谢您。

rqmkfv5c

rqmkfv5c1#

就给吧 unsignedrole_id . 改变

$table->integer('role_id');

进入之内

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

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

guykilcj

guykilcj2#

用于管理 foreign key 关系两个表必须具有相同的数据类型列,并且父表列必须是 primary key 或者一个 index column . 对你来说 role_id 列是一个整数,在 usersid 列不是整数,这就是错误的原因。
所以让这两列在 datatype 再试一次。

ttygqcqt

ttygqcqt3#

必须使用unsignedinteger来定义角色\u id,因为它在数据库中是无符号int(使用增量)。然后尝试迁移。

$table->unsignedInteger('role_id');

相关问题