1

我有几个 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

问题是什么?

4

3 回答 3

1

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

于 2015-05-05T15:54:08.153 回答
1

这个问题的解决方案。
添加到 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

于 2018-09-04T06:13:13.760 回答
0

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

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

如果不使用unsigned();方法,字段将由 int(11) 类型创建,并且与 int(10) 不匹配

于 2015-05-05T20:16:13.603 回答