Laravel - errno: 150 外键约束的格式不正确 - 一对多关系

问题描述

我有两个模型:Concorso 和 State。关系如下: Concorso 属于一个国家;一个州有很多 Concorso。 请注意,Concorsi 是 Concorso 的复数形式。

create_concorsi_table

public function up()
    {
        Schema::create('concorsi',function (Blueprint $table) {
            $table->id();
            $table->foreignId('state_id')->constrained();
            $table->string('nome');
            $table->text('descrizione');
            $table->date('data_accettazione');
            $table->date('data_scadenza');
            $table->timestamps();
        });
    }



create_states_table

  public function up()
    {
        Schema::create('states',function (Blueprint $table) {
            $table->id();
            $table->string('status');
            $table->timestamps();
        });
    }



当我运行“PHP artisan migrate”时,我收到了这个错误

sqlSTATE[HY000]: General error: 1005 Can't create table `inertia_example_1`.`concorsi` (errno: 150 "Foreign key constraint is incorrectly formed") (sql: alter table `concorsi` add constraint `concorsi_state_id_foreign` foreign key (`state_id`) references `states` (`id`))

我真的无法理解这个问题。语法似乎正确,可能是什么问题?

谢谢!

解决方法

Concorsi 的创作需要状态。迁移创建过程是顺序的。检查migrations in Laravel