1

I have a couple of Laravel migrations.

1-create_countries_table`

Schema::create('countries', function(Blueprint $table)
{
    $table->increments('id');
        $table->string('name');
    $table->timestamps();
});

2-create_cities_table

Schema::create('cities', function(Blueprint $table)
{
    $table->increments('id');
        $table->string('name');
        $table->smallInteger('country_id');
    $table->timestamps();
        $table->foreign('country_id')->references('id')->on('countries');
});

When I use php artisan migrate , I see this error

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
 (SQL: alter table `cities` add constraint cities_country_id_foreign
 foreign key (`country_id`) references `countries` (`id`))

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

What is the problem?

1
  • Shouldn't refrences('id') be references('id')? Commented May 5, 2015 at 15:54

3 Answers 3

1

Try $table->integer('country_id')->unsigned(); instead of $table->smallInteger('country_id');

Sign up to request clarification or add additional context in comments.

4 Comments

I do that but i have the same problem. I think the problem cause is laravel generate mysql query that dose not accept from mysql query syntax.
It should generate the right syntax if you selected the right driver in config files (mysql is the default I believe). Your error message seems to have a space after countries, double check to make sure its not the case in the migration.
I checked it out . and change refrence to references but steel i have problem.
Did you figure it out? what was the problem?
1

solution for this problem.
add to app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

public function boot(){
    Schema::defaultStringLength(191);
}

https://laravel-news.com/laravel-5-4-key-too-long-error

Comments

0

In the laravel when use $table->increments('id'); Laravel create a int(10) field. to connect a field to an id as foregin key it must be int(10). for make a foreign key int 10 we muste use this code:

$table->integer('country_id')->unsigned();

if dont use unsigned(); method, a field will create by int(11) type and isn't mach to int(10)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.