A
A
ashfedor2020-03-28 11:12:05
Database migration
ashfedor, 2020-03-28 11:12:05

How to solve Laravel migration error?

I will write right away that laravel has just started to study.
I create a clean project on Laravel 6. I create a database and register it in .env.
create migration file

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBlogsTable extends Migration
{
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('content');
            $table->integer('user_id');
            $table->timestamps();
            
            $table->foreign('user_id')
                  ->references('id')
                  ->on('users');
        });
    }
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}


doing php artisan migrate command and

getting Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `blogs` add constraint `blogs_user_id_foreign` foreign key (`user_id`) references ` users` (`id`))
The foreign key is not added,
is it that it does not work from a version higher than 5.8?
How to solve it, or score and register the connection in the models. While I’m teaching Lara, so if I wrote it wrong, don’t throw slippers))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-03-28
@ashfedor

Is it that it does not work from a version above 5.8?

Approximately from this version, Laravel began to generate migrations with bigIncrements ids, then it fell down for many (who did not read the description of the upgrade, of course)) as Aleksey correctly answered, write in blogs
$table->bigInteger('user_id')->unsigned();
on Laravel 6

It's better to start from the 7th. compared to the 6th, there are moments where you can then run into refactoring)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question