【问题标题】:Laravel Migration Error on foreign key constraint外键约束上的 Laravel 迁移错误
【发布时间】:2019-12-24 07:46:30
【问题描述】:

我在运行 Laravel 项目的迁移时遇到问题。当我运行工匠迁移时,它在外键中停止。有人可以帮我弄这个吗?我尝试了其他类似问题的解决方案,但它不起作用。

错误消息:SQLSTATE[HY000]:一般错误:1005 无法创建表。

airways.#sql-4588_cfb (errno: 150 "外键约束格式不正确") (SQL: alter table flights add constraint flights_airport_departure_foreign 外键(airport_departure)在删除级联时引用airports(airport_code)

flights_table.php

 public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->integer('flight_number')->primary();
            $table->string('airline');
            $table->integer('airport_departure')->unsigned();
            $table->string('departure_time');
            $table->integer('airport_arrival')->unsigned();
            $table->string('arrival_time');
            $table->string('flight_duration');
            $table->timestamps();
        });

        Schema::table('flights', function($table) {
            $table->foreign('airport_departure')
                  ->references('airport_code')->on('airports')
                  ->onDelete('cascade');

                  $table->foreign('airport_arrival')
                  ->references('airport_code')->on('airports')
                  ->onDelete('cascade');
        });
    }


airports_table.php

  public function up()
    {
        Schema::create('airports', function (Blueprint $table) {
            $table->integer('airport_code')->primary();
            $table->string('airport_name');
            $table->string('airport_location');
            $table->string('airport_state');
            $table->timestamps();
        });
    }

【问题讨论】:

  • 检查您的迁移顺序。需要先迁移airports表,再迁移flights表。
  • 先生,我的代码没有问题吗?
  • 好像没有。检查两个迁移文件的时间戳。如果航班迁移时间戳大于 airports 表,则使其小于 airports 表。
  • 尝试从外键列中删除无符号方法$table->integer('airport_departure')->unsigned();
  • @Vince,codebuilders 已经回答了你的问题。但我想你只是错过了。

标签: mysql sql laravel foreign-keys schema


【解决方案1】:

您的外键列类型错误。您没有将 airport_code 设置为无符号整数,但 airport_departure 和 airport_arrival 需要无符号整数。此外,您需要在创建航班表之前创建机场表,而不是其他人建议的“轮回”。

【讨论】:

  • 我明白了。所以我需要在我的airport_code 列中添加unsigned。现在是$table->integer('airport_code')->primary()->unsigned(); 现在它可以工作了。
【解决方案2】:

回滚你的迁移,改变迁移的顺序,即如果airport table是2014_10_12_0000,flighting_table是2014_10_12_00001,把airport table改为0002。

【讨论】:

  • 我回滚了我的迁移先生,但是当我执行迁移命令时,它仍然得到同样的错误。
  • 先生,我已经对我的迁移文件进行了更改。机场表时间戳现在大于航班表。它仍然给我同样的错误。
猜你喜欢
  • 2016-03-03
  • 1970-01-01
  • 2018-04-05
  • 2020-01-20
  • 2013-09-10
  • 2020-12-23
  • 2020-04-04
  • 1970-01-01
  • 2022-11-27
相关资源
最近更新 更多