我有文件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上也读过类似的问题,但都没用。你知道这是什么原因吗?谢谢您。
3条答案
按热度按时间uinbv5nw1#
用于管理
foreign key
关系两个表必须具有相同的数据类型列,并且父表列必须是primary key
或者一个index column
. 对你来说role_id
列是一个整数,在users
表id
列不是整数,这就是错误的原因。所以让这两列在
datatype
再试一次。vq8itlhq2#
就给吧
unsigned
在role_id
. 改变进入之内
这是因为外键是无符号整数。
iszxjhcz3#
必须使用unsignedinteger来定义角色\u id,因为它在数据库中是无符号int(使用增量)。然后尝试迁移。