How to make Foreign Keys using Migrations Laravel

Asked

Viewed 392 times

0

I’m trying to relate one field to another using Migrations this way:

inserir a descrição da imagem aqui

But when doing foreign key in Migrations this way:

Migration Permission:

  Schema::create('permissions', function (Blueprint $table) {
          $table->increments('id');

          $table->index('user_id');

          $table->timestamps();
    });

Migration User:

    Schema::create('users', function (Blueprint $table) {
        $table->string('id', 100)->primary();

        // Código Omitido...
    });

    Schema::table('permissions', function($table) {
         $table->foreign('user_id')->references('id')->on('users');
     });

Error I Receive in terminal:

Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'user_id' doesn't exist in table (SQL: alter tablePermissionsadd indexpermissions_user_id_index(user_id)) 1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'user_id' doesn't exist in table") D:\Infinity\vendor\laravel\framework\src\Illuminate\Database\Connection.php : 458 2 PDOStatement::execute() D:\Infinity\vendor\laravel\framework\src\Illuminate\Database\Connection.php : 458

  • 1

    your Migration is missing the field user_id? the error showing is this ... only has this code?

  • 1

    beyond this problem, I believe that the relationship could be many for many!

  • @Virgilionovic is not missing the user_Id it is declared in the Permissions. Only these same codes

  • @Virgilionovic But it’s not that relationship that’s being made?

  • 1

    The relationship seems to me by drawing, 1 for many! it is good you put the Migration correctly, because, it seems to me that there is code inside the wrong place that also causes problems in the generation of the physical model.

  • @Virgilionovic I made two Migrations one from the Permissions table and the other from Users, in Users' Migration the list is made because I need the two tables made to have the relation

Show 1 more comment

1 answer

1


You forgot to set the column user_id.

Note that you just set user_id as Indice, but did not create the column before that.

  Schema::create('permissions', function (Blueprint $table) {
          $table->increments('id');

          $table->index('user_id');

          $table->timestamps();
    });

Make the following replacement:

  Schema::create('permissions', function (Blueprint $table) {
          $table->increments('id');

          $table->integer('user_id');
          $table->index('user_id');

          $table->timestamps();
    });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.