I am currently receiving the following error when I run my migrations:
SQLSTATE[HY000]: General error: 1005 Can't create table 'saferides.#sql-189_4bc' (errno: 150) (SQL: alter table `rides` add constraint rides_car_id_foreign foreign key (`car_id`) references `car` (`id`) on delete cascade)
After reading a lot of issues about errors of this nature in Laravel, I have done the following to avoid it:
Currently, I have my migrations set up so that the tables are created first:
// Up function for cars table
public function up()
{
Schema::create('cars', function(Blueprint $table)
{
// Explicitly state storage engine
$table->engine = 'InnoDB';
// Primary Key
$table->increments('id')->unsigned();
// Other columns
$table->string('car_num');
$table->string('available_seats');
// Indexes to foreign keys
$table->integer('user_id')->unsigned()->index();
$table->integer('ride_id')->unsigned()->index();
});
}
// Up function for rides table
public function up()
{
Schema::create('rides', function(Blueprint $table)
{
// Explicitly state storage engine
$table->engine = 'InnoDB';
// Primary Key
$table->increments('id')->unsigned();
// Other columns
$table->boolean('completed')->default(0);
$table->boolean('no_show')->default(0);
// Indexes to foreign keys
$table->integer('location_id')->unsigned()->index();
$table->integer('user_id')->unsigned()->index();
$table->integer('car_id')->unsigned()->index();
});
}
After all my tables are created, I add my foreign keys to the tables.
public function up()
{
Schema::table('cars', function(Blueprint $table)
{
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('ride_id')
->references('id')->on('rides')
->onDelete('cascade');
});
}
public function up()
{
Schema::table('rides', function(Blueprint $table)
{
$table->foreign('location_id')
->references('id')->on('locations')
->onDelete('cascade');
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('car_id')
->references('id')->on('car')
->onDelete('cascade');
});
}
Any advice on how to fix this would be appreciated.
The table you reference in the last foreign key statement is 'car' but the table is 'cars'.
Does this help?
This issue hasn't even been fixed in 5.1. What can we do to have Tyler fix this in the next release?
As I see, this is not a laravel issue, this is a MySQL issue.
IMHO, is not a bug, its a detail of implementation: you cannot reference a FK to a yet-not-created table and table PK.
The way around that is simple: order your migrations to guarantee that all FK declarations references pre-created tables.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community