jerney
jerney

Reputation: 2233

Issue with Laravel Migrations and Foreign Keys

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

Then my next table...

// 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('car_id')->unsigned()->index();
   });
}

After all my tables are created, I add my foreign keys to the tables.

public function up()
{
    Schema::table('rides', function(Blueprint $table) 
    {
        $table->foreign('car_id')
              ->references('id')->on('car')
              ->onDelete('cascade');
    });
}

Any advice on how to fix this would be appreciated.

Upvotes: 0

Views: 1305

Answers (2)

Logan Bailey
Logan Bailey

Reputation: 7127

You're specify the car table but the table name is cars.

public function up()
{
    Schema::table('rides', function(Blueprint $table) 
    {
        $table->foreign('car_id')
              ->references('id')->on('cars')
              ->onDelete('cascade');
    });
}

Upvotes: 1

jerney
jerney

Reputation: 2233

If anyone in the future is having this issue, I managed to bypass this issue by dropping all of my foreign key restraints. While I still have foreign key indexes that refer to other tables, as far as my mySQL database is concerned, this is just field that holds an unsigned integer. I enforce the relationships between my models in my application like this, and it has worked for me so far.

Upvotes: 1

Related Questions