【问题标题】:Laravel migration error SQLSTATE[42000]Laravel 迁移错误 SQLSTATE[42000]
【发布时间】:2015-07-15 11:07:39
【问题描述】:

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

有什么问题?

【问题讨论】:

  • 不应该refrences('id')references('id')

标签: mysql laravel pdo artisan-migrate


【解决方案1】:

尝试$table->integer('country_id')->unsigned(); 而不是$table->smallInteger('country_id');

【讨论】:

  • 我这样做了,但我有同样的问题。我认为问题原因是 laravel 生成不接受 mysql 查询语法的 mysql 查询。
  • 如果您在配置文件中选择了正确的驱动程序,它应该会生成正确的语法(我相信mysql是默认的)。您的错误消息似乎在国家之后有一个空格,请仔细检查以确保它不是迁移中的情况。
  • 我检查过了。并将参考更改为参考,但钢铁我有问题。
  • 你弄明白了吗?出了什么问题?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 1970-01-01
      • 2018-10-15
      • 2018-02-06
      • 2013-02-02
      • 2023-02-10
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多