Проблема, когда я запускаю «artisan: migrate» в отношениях «Многие к одному»

#php #laravel

#php #laravel

Вопрос:

У меня есть таблица «люди», и у каждого «человека» должна быть какая-то «мебель».

Я запускаю «migrate», и появляется это сообщение об ошибке:

QLSTATE [HY000]: Общая ошибка: 1005 Не удается создать таблицу my_database . furniture (ошибка: 150 «Неправильно сформировано ограничение внешнего ключа») (SQL: alter table furniture добавить ограничение furniture_person_id_foreign внешнего ключа ( person_id ) ссылки people ( id ))

ВЕРСИЯ LARAVEL: 5.8

Вот мои файлы:

2021_04_15_132404_create_persons_table.php

 <?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreatePeopleTable extends Migration
{
   
    public function up()
    {
        Schema::create('people', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('cpf');
            $table->string('phone');
            $table->softDeletes();      
            $table->timestamps();          
        });
    }
  
   
    public function down()
    {
        Schema::dropIfExists('people');
    }
}
 

2021_04_16_233323_create_furniture_table.php

 <?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateFurnitureTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('furniture', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('type');
            $table->string('name');
            $table->integer('person_id')->unsignedBigInteger()->nullable();
            $table->foreign('person_id')->references('id')->on('people');
            $table->softDeletes();   
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('furniture');
    }
}
 

Person.php

 <?php

namespace App;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class Person extends Model
{
    use SoftDeletes;
  
    
}
 

Furniture.php

 <?php

namespace App;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class Furniture extends Model
{
    use SoftDeletes;
}
 

Кто-нибудь знает, как решить?

Ответ №1:

Удалите $table->integer('person_id')->nullable(); из CreateFurnitureTable миграции, оставьте unsignedBigInteger , поскольку это тип столбца integer. Просто используя этот метод, который мы также рекомендуем Laravel в соответствии с документацией по внешним ключам для Laravel 5.8

 $table->unsignedBigInteger('person_id');

$table->foreign('person_id')->references('id')->on('people');
 

Комментарии:

1. Возвращено сообщение об ошибке: Метод Illuminate Database Schema Blueprint:: foreignId не существует. Этот метод может отсутствовать в версии 5.8. это версия, которую я использую. Не так ли?

2. Обновленный ответ для Laravel v5.8.