SQLSTATE [HY000]:一般错误:在Laravel迁移期间出现1005

我正在使用Laravel6。我想运行迁移文件,但是在迁移“ create_users_table”文件时出现以下错误:

SQLSTATE[HY000]: General error: 1005 Can't create tab
le `thenewmeetingapp`.`#sql-f3c_b8` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table 
`users` add constraint `users_permission_id_foreign` foreign key (`permission_id`) references `permissions` (`id`))

我认为错误在于表“ users”和表“ permissions”之间(每个用户必须有一个许可,每个许可可以有许多用户)。 但是,表“用户”与表“ meeting_user”也相关,表“ meeting_user”是与表“ meetings”连接的表。

用户:

Schema::create('users',function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('surname');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('username')->unique();
            $table->string('password');
            $table->bigInteger('permission_id')->unsigned();
            $table->enum('is_active',array(0,1))->default(1);
            $table->rememberToken();
            $table->timestamps();
            $table->foreign('permission_id')->references('id')->on('permissions');

        });

权限:

Schema::create('permissions',function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });

会议用户:

Schema::create('meeting_user',function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('meeting_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('meeting_id')->references('id')->on('meetings')->onDelete('cascade');
        });

用户表的迁移是要运行的第一个迁移。但是,我也尝试在权限表迁移之前和用户的权限表迁移之后运行,但没有任何变化。错误是相同的。 有人可以帮助我吗?

snailtoto 回答:SQLSTATE [HY000]:一般错误:在Laravel迁移期间出现1005

您需要先创建users上指向外键的另一个表permissions,然后才能将键添加到users。因此,创建users表的特定迁移不能首先进行。另一个表permissions必须存在,然后才能引用它。

如果您无法对这些迁移进行重新排序,则可以从users迁移中删除外键部分。然后创建一个新的迁移,以更改users表并添加外键;现在permissions表迁移之后,该文件将(通过时间戳记)运行。

,

如@lagbox的答案所解释,您无法为尚不存在的表中的列创建外键。
因此,我建议的方法是更改​​迁移顺序,更改每个迁移文件名的时间戳,以便按以下顺序执行它们:

  1. permissions
  2. users
  3. meetings
  4. meeting_user

请注意,更改文件名后,必须运行composer dump-autoload,然后再次运行迁移。

本文链接:https://www.f2er.com/3043775.html

大家都在问