首页 > 解决方案 > SQLSTATE[HY000]: errno: 150 "外键约束格式不正确

问题描述

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

标签: mysqllaravelmigration

解决方案


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

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

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

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

推荐阅读