【问题标题】:Laravel - errno: 150 Foreign key constraint is incorrectly formed - One to Many relationshipLaravel - errno:150 外键约束形成错误 - 一对多关系
【发布时间】:2021-07-22 15:57:45
【问题描述】:

我有两个模型: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`))

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

谢谢!

【问题讨论】:

  • 顺序很重要。如果要引用它,请先创建 states
  • 现在可以了!但是,为了让“状态”迁移在另一个之前生成,我用更早的日期重命名了迁移文件。除了重命名迁移文件之外还有其他方法吗?或者这是正确的方法吗?跨度>
  • 这是正确的方法,很高兴它有效

标签: laravel eloquent foreign-keys


【解决方案1】:

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

【讨论】:

  • 现在可以了!但是,为了让“状态”迁移在另一个之前生成,我用更早的日期重命名了迁移文件。除了重命名迁移文件之外还有其他方法吗?或者这是正确的方法吗?跨度>
  • 迁移对于避免修改文件和不丢失存储的数据非常有用。这就像在数据库中保存更改的存储库。但为此,请提出另一个问题。 @nicoblue
猜你喜欢
  • 2021-07-27
  • 2020-02-10
  • 2021-08-06
  • 2021-01-05
  • 2021-12-24
  • 2020-12-19
  • 2020-07-22
  • 2017-04-13
  • 2019-09-17
相关资源
最近更新 更多