SQLSTATE [HY000]:错误:150“外键约束格式不正确

时间:2019-09-03 10:54:03

标签: mysql laravel migration

我尝试进行迁移 而我的错误是“ 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');
    });
}

1 个答案:

答案 0 :(得分:3)

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

  

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

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

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