首页 > 解决方案 > 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();
        });
    }



创建状态表

  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`))

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

谢谢!

标签: laraveleloquentforeign-keys

解决方案


Concorsi 需要状态来进行他的创作。迁移创建过程是连续的。在 Laravel 中检查迁移


推荐阅读