Set name for a Foreign Key created from a Migration in Laravel

Asked

Viewed 511 times

1

I am building an application using Laravel 5.1 and in my ER Diagram it is very deep and detailed (even with index nomenclature). I need to know how to create a Foreign Key using the Migration methods of the Laravel in which I can define the name of the same, maybe something like:

Schema::create('historico', function (Blueprint $table) {
    $table->increments('id');
    $table->dateTime('data_reg')
          ->default(DB::raw('CURRENT_TIMESTAMP'));
    $table->integer('usuario_id');
    $table->foreign('usuario_id')
          ->foreignName('historico$usuario_id') // <-- procuro isso aqui
          ->references('id')
          ->on('usuario')
          ->onDelete('CASCADE')
          ->onUpdate('CASCADE');
    $table->string('acao', 500);
    $table->longText('conteudo')->nullable();
});
  • If the answer solved the problem, please consider marking it. Then we will know that it was useful for you and will have a better view by the other user.

1 answer

3


Pass a second parameter in the Foreign() function. Example:

$table->foreign('usuario_id', 'nome_da_foreign_key') // o que você procura
          ->references('id')
          ->on('usuario')
          ->onDelete('CASCADE')
          ->onUpdate('CASCADE');

You can see the prototype of the Foreign key function in the Blueprint.php file of the Laravel:

/**
     * Specify a foreign key for the table.
     *
     * @param  string|array  $columns
     * @param  string  $name
     * @return \Illuminate\Support\Fluent
     */
    public function foreign($columns, $name = null)
    {
        return $this->indexCommand('foreign', $columns, $name);
    }

Browser other questions tagged

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