php - 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上读过类似的问题,但没有任何效果。对造成这种情况的原因有任何了解吗?谢谢你。
解决方案
您必须将 unsignedInteger 用于 role_id,因为它在您的数据库中是 unsinged int (您使用增量)。然后尝试迁移。
$table->unsignedInteger('role_id');
推荐阅读
- pip - 获取 pip 包的 Yum/RPM 版本 (django-tables2)
- javascript - 无法在 Axios 调用之外获得价值
- c# - 交叉继承实现与EF Core 3.0
- corda - Docker 网络,没有目标提供可接受的证书
- python - 使用 Python 解析 XML 文档
- angular - Angular 响应式从到日期
- sql - 如何选择表上唯一的日期/字符串
- arguments - 请解释 Octave-Error : operator /: nonconformant arguments (op1 is 1x1, op2 is 1x10)
- json - 无法解析从 Dir.glob 获得的文件
- python - 在 python 中进行装饰时返回函数的原因是什么?