Laravel迁移错误SQLSTATE [42000]

时间:2015-05-05 15:49:13

标签: mysql laravel pdo artisan-migrate

我有几个Laravel迁移。

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

当我使用php artisan migrate时,我看到此错误

  [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

有什么问题?

3 个答案:

答案 0 :(得分:1)

尝试使用$table->integer('country_id')->unsigned();代替$table->smallInteger('country_id');

答案 1 :(得分:0)

在laravel中使用$table->increments('id');时,Laravel会创建一个int(10)字段。 要将字段连接到id作为foregin键,它必须是int(10)。对于make一个外键int 10,我们使用这段代码:

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

如果不使用unsigned();方法,则字段将按int(11)类型创建,而不是mach到int(10)

答案 2 :(得分:0)

解决此问题的方法。
添加到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