Ad
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');
});
}
Ad
Answer
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();
Ad
source: stackoverflow.com
Related Questions
- → I can't do a foreign key, constraint error
- → How to implement DbDongle::convertTimestamps as workaround of invalid timestamps with MySql strict
- → MySQL error "Foreign key constraint is incorrectly formed"
- → Eloquent Multitable query
- → "Laravel 5.1" add user and project with userId
- → Database backup with custom code in laravel 5 and get the data upto 10 rows from per table in database
- → Laravel 5.1 QueryException when trying to delete a project
- → Using Array in '->where()' for Laravel Query Building
- → Chaining "Count of Columns" of a Method to Single Query Builder
- → Laravel Eloquent Joining Strange query
- → convert time using mysql laravel 5
- → How to update a column after an expiration date in MySQL?
- → Foreign key constraint fails on existing key
Ad