php:laravel不能添加外键约束

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

我有文件2018\u 08\u 23\u 042408\u create\u roles\u table.php

  1. use Illuminate\Support\Facades\Schema;
  2. use Illuminate\Database\Schema\Blueprint;
  3. use Illuminate\Database\Migrations\Migration;
  4. class CreateRolesTable extends Migration
  5. {
  6. public function up()
  7. {
  8. Schema::create('roles', function (Blueprint $table) {
  9. $table->increments('id');
  10. $table->string('role_name');
  11. $table->string('description');
  12. $table->timestamps();
  13. });
  14. }
  15. public function down()
  16. {
  17. Schema::drop('roles');
  18. }
  19. }

和2018\u 08\u 23\u 042521\u create\u users\u table.php

  1. <?php
  2. use Illuminate\Support\Facades\Schema;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Database\Migrations\Migration;
  5. class CreateUsersTable extends Migration
  6. {
  7. public function up()
  8. {
  9. Schema::create('users', function (Blueprint $table) {
  10. $table->increments('id');
  11. $table->string('fullname');
  12. $table->string('email')->unique();
  13. $table->string('username')->unique();
  14. $table->string('password');
  15. $table->string('avatar_link');
  16. $table->integer('role_id');
  17. $table->foreign('role_id')->references('id')->on('roles');
  18. $table->rememberToken();
  19. $table->timestamps();
  20. });
  21. }
  22. public function down()
  23. {
  24. Schema::table('role_user', function (Blueprint $table) {
  25. $table->dropForeign(['role_id']);
  26. });
  27. Schema::drop('users');
  28. }
  29. }

然而,当我运行php artisan migrate时,我遇到了这个错误

  1. [Illuminate\Database\QueryException]
  2. SQLSTATE[HY000]: General error: 1215 Cannot add foreign key
  3. constraint (SQL
  4. : alter table `users` add constraint `users_role_id_foreign` foreign
  5. key (`role_id`) references `roles` (`id`))
  6. [PDOException]
  7. SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

当我运行php时artisan:reset it 总是显示错误,比如“基表存在”,我必须运行php artisan tinker和schema::drop('users')来修复这个错误。我在stackoverflow上也读过类似的问题,但都没用。你知道这是什么原因吗?谢谢您。

uinbv5nw

uinbv5nw1#

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

vq8itlhq

vq8itlhq2#

就给吧 unsignedrole_id . 改变

  1. $table->integer('role_id');

进入之内

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

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

iszxjhcz

iszxjhcz3#

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

  1. $table->unsignedInteger('role_id');

相关问题