How to make Foreign Keys using Migrations Laravel

0

I'm trying to relate one field to another using migrations this way:

  

Butwhendoingtheforeignkeyinmigrationsthisway:

MigrationPermission:

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

MigrationUser:

Schema::create('users',function(Blueprint$table){$table->string('id',100)->primary();//CódigoOmitido...});Schema::table('permissions',function($table){$table->foreign('user_id')->references('id')->on('users');});

Errorgettingterminal:

  

Illuminate\Database\QueryException:SQLSTATE[42000]:Syntaxerrororaccessviolation:1072Keycolumn'user_id'doesn'texistintable(SQL:altertablepermissionsaddindexpermissions_user_id_index(user_id))1PDOException::("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

    
asked by anonymous 13.03.2018 / 21:09

1 answer

0

You forgot to set the user_id column.

Note that you just set user_id to index, 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 substitution:

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

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

          $table->timestamps();
    });
    
30.12.2018 / 14:36