У меня проблема миграции, когда тип поля - строка SQLSTATE [HY000]: общая ошибка: 1215 - PullRequest
0 голосов
/ 02 июля 2019
In Connection.php line 664:
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `point_deliveries` add constraint `point_d
  eliveries_city_ref_foreign` foreign key (`city_ref`) references `cities` (`ref`))

In Connection.php line 458:
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

Я связываю таблицы так ...

//parent
Schema::create('cities', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title')->nullable();
            $table->string('ref');
            $table->integer('country_id')->index()->unsigned()->nullable();
            $table->foreign('country_id')->references('id')->on('countries');
        });

//child
Schema::create('point_deliveries', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('title')->nullable();
            $table->string('ref')->nullable();
            $table->string('city_ref');
            $table->foreign('city_ref')->references('ref')->on('cities');
        });

как их связать?Нет проблем с полем integer.

Ответы [ 3 ]

1 голос
/ 02 июля 2019

Столбец должен быть проиндексирован

Чтобы создать ограничение внешнего ключа, столбец таблицы, на которую вы ссылаетесь, должен быть проиндексирован. Я бы посоветовал вам сделать поле ref уникальным в таблице городов, указав для него индекс и обеспечив, чтобы у вас был только один элемент для ссылки.

//parent
Schema::create('cities', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title')->nullable();
            $table->string('ref')->unique();;
            $table->integer('country_id')->index()->unsigned()->nullable();
            $table->foreign('country_id')->references('id')->on('countries');
        });

//child
Schema::create('point_deliveries', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('title')->nullable();
            $table->string('ref')->nullable();
            $table->string('city_ref');
            $table->foreign('city_ref')->references('ref')->on('cities');
        });
1 голос
/ 02 июля 2019

Вы можете иметь только внешний ключ, ссылающийся на уникальное поле.Измените таблицу городов так, чтобы поле ref было уникальным, например:

// cities

$table->string('ref')->unique();
0 голосов
/ 02 июля 2019

Убедитесь, что для механизма таблиц по умолчанию установлено InnoDB или задано явно с помощью $ table-> engine = 'InnoDB';

Также здесь приведены документы для 5.8, надеюсь, это поможет вам.

https://laravel.com/docs/5.8/migrations

...