【问题标题】:SQLSTATE[HY000]: errno: 150 "Foreign key constraint is incorrectly formedSQLSTATE[HY000]: errno: 150 "外键约束格式不正确
【发布时间】:2020-01-06 06:36:11
【问题描述】:

我尝试进行迁移 我的错误是“errno: 150”外键约束格式不正确” 我无法解释更多,但我应该为堆栈验证长度编写 smt

及其我的代码:

public function up()
{
    Schema::create('bus_lines', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title',20)->collation('utf8_persian_ci');
        $table->unsignedInteger('code');
        $table->integer('start_station');
        $table->integer('end_station');
        $table->smallInteger('pub');
        $table->smallInteger('rmv');
        $table->timestamps();

        });
}


public function up()
{
    Schema::create('station_buses', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title',30);
        $table->unsignedInteger('code');
        $table->timestamps();

    });
}

public function up()
{
    Schema::create('busline_stationbus', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedInteger('line_code');
        $table->unsignedInteger('station_code');
        $table->timestamps();


        $table->foreign('line_code')->references('code')->on('bus_lines')->onDelete('cascade');
        $table->foreign('station_code')->references('code')->on('station_buses')->onDelete('cascade');
    });
}

【问题讨论】:

    标签: mysql laravel migration


    【解决方案1】:

    因此,如果将外键应用于非主键,则必须将其应用于唯一列:

    FOREIGN KEY 约束不必只链接到另一个表中的 PRIMARY KEY 约束;它也可以定义为引用另一个表中 UNIQUE 约束的列。

    所以你在两个表中的code 应该是这样的:

    $table->unsignedInteger('code')->unique();
    

    【讨论】:

      猜你喜欢
      • 2018-06-19
      • 2018-03-02
      • 2020-07-07
      • 1970-01-01
      • 2017-04-13
      • 2018-09-04
      • 2019-09-17
      • 2020-12-16
      相关资源
      最近更新 更多