alireza alizade
alireza alizade

Reputation: 477

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

Upvotes: 1

Views: 72

Answers (1)

nakov
nakov

Reputation: 14278

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();

Upvotes: 3

Related Questions