@Eternal97

В чем может быть причина ошибки при миграции базы данных SQLSTATE[HY000]: General error: 1005?

Всем доброго времени суток. Выходит ошибка при запуске миграций такого вида:
Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table
 `check_lists`.`tasks` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `tasks` add
 constraint `tasks_checklist_id_foreign` foreign key (`checklist_id`) references `checklists` (`id`) on delete
 cascade)

На просторах интернета нашел множество советов, но не один не помог. Структура моих миграций следующая:
1. Таблица Users:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

2. Таблица checklists:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateChecklistsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('checklists', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');
            $table->string('title');
            $table->timestamps();
        });
    }

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

3. Таблица Tasks:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('checklist_id');
            $table->foreign('checklist_id')
                ->references('id')->on('checklists')
                ->onDelete('cascade');
            $table->string('message');
            $table->boolean('completed');
            $table->timestamps();
        });
    }

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

Отношения в моделях прописал следующим образом:
1. Модель User:
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function checklists() 
    {
        return $this->hasMany(Checklist::class);
    }
}

2. Модель Checklist:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Checklist extends Model
{
    protected $guarded = [];

    public function user ()
    {
    	return $this->belongTo(User::class);
    }

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }
}

3. Модель Task:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $guarded = [];

    public function checklist ()
    {
    	return $this->belongTo(Checklist::class);
    }
}

Порядок выполнения миграций до ошибки следующий:
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.08 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (0.07 seconds)
Migrating: 2021_02_01_171453_create_tasks_table

Если убираю ограничение внешнего ключа, то миграции проходят успешно.
В чем может быть косяк? Заранее большое всем спасибо!
  • Вопрос задан
  • 513 просмотров
Пригласить эксперта
Ответы на вопрос 1
Sanes
@Sanes
Попробуйте
$table->foreignId('checklist_id')
      ->constrained()
      ->onDelete('cascade');

Вместо
$table->unsignedBigInteger('checklist_id');
$table->foreign('checklist_id')
          ->references('id')->on('checklists')
          ->onDelete('cascade');
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы