Laravel 无法创建迁移文件 2 外键

Laravel migration file 2 foreign keys can not be created

我正在尝试创建一个新的 table,其中将设置 2 个外键

 public function up()
    {
        Schema::create('role_permissions_link', function (Blueprint $table) {
            $table->id();
            $table->integer('permissions_id')->unsigned();
            $table->integer('users_role_id')->unsigned();
            $table->timestamps();
            $table->index(['permissions_id', 'users_role_id']);
        });

        Schema::table('role_permissions_link', function (Blueprint $table) {
            $table->foreign('permissions_id')->references('id')->on('permissions');
            $table->foreign('users_role_id')->references('id')->on('users_role');
        });
    }

我一直收到错误提示

SQLSTATE[HY000]: General error: 1005 Can't create table `homestead`.`ja_role_permissions_link` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `ja_role_permissions_link` add constraint `ja_role_permissions_link_permissions_id_foreign` foreign key (`permissions_id`) references `ja_permissions` (`id`))

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673| 

      +9 vendor frames 
  10  database/migrations/2020_04_06_144324_create_role_permissions_link_table.php:27
      Illuminate\Support\Facades\Facade::__callStatic()

      +34 vendor frames 
  45  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

我试过移动代码和一些在线解决方案,但总是出现同样的错误。

权限迁移文件

 public function up()
    {
        Schema::create('permissions', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
            $table->index(['id']);
        });
    }

users_role 迁移文件

public function up()
{
    Schema::create('users_role', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
        $table->index(['id']);
    });
}

解决方案 1 - 数据类型~(这次不行!)~~

需要检查的是您的列和键的数据类型是否匹配。

如果一个 table 上的外键(即 $table->integer('permissions_id')->unsigned();)与另一个 table 上的 ID 不匹配($table->bigIncrements('id');)


解决方案 2 - 迁移顺序正确

permissions 应该在 role_permissions 之前。您可能需要稍微重命名迁移,因为它们将 运行 根据它们的名称按日期顺序排列。