簡體   English   中英

PHP:Laravel無法添加外鍵約束

[英]PHP: Laravel Cannot add foreign key constraint

我有文件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的類似問題,但沒有任何效果。 什么原因造成的任何見解? 謝謝。

您必須將unsignedInteger用作role_id,因為它在數據庫中是unsinged int的(使用增量)。 然后嘗試遷移。

$table->unsignedInteger('role_id');

只需在role_id上提供unsigned 更改

$table->integer('role_id');

進入

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

這是因為外鍵是無符號整數。

為了管理foreign key關系,兩個表必須具有相同的數據類型列,而父表列必須是primary keyindex column 在您的情況下, role_id列是整數,而在users表中, id列不是整數,這就是錯誤的原因。

因此,使這兩列在datatype方面相同,然后重試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM