简体   繁体   中英

SQLSTATE[HY000]: errno: 150 "Foreign key constraint is incorrectly formed

I try to make migration and my error is "errno: 150 "Foreign key constraint is incorrectly formed" I cant explain more than this but I should write smt for stack validate length

and its my code:

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');
    });
}

So if the foreign key is applied to a non primary key it has to be applied to a unique column:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

So your code in both tables should be this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM