简体   繁体   中英

Correct way to name UNIQUE, INDEX, FOREING KEYS on LARAVEL 5.6

I have this code for my migrations on LARAVEL:

public function up()
{
    Schema::create('estados', function (Blueprint $table) {
        $table->bigIncrements('id')->primary('PRIMARY');
        $table->string('nombre' , 30)->nullable();
        $table->unique('nombre' , 'nombre_u');
        $table->integer('pais_id')->default('1');
        $table->foreign('pais_id' , 'pais_id_fk')->refereces('id')->on('paises');
        $table->index('pais_id' , 'pais_id_fk_idx');
    });
}

How can I improve my code? Idk how to set, for example, the next 2 lines as UNIQUE in the same line:

$table->string('nombre' , 30)->nullable();
$table->unique('nombre' , 'nombre_u');

Or these 3 lines into only 1 line:

$table->integer('pais_id')->default('1');
$table->foreign('pais_id' , 'pais_id_fk')->refereces('id')->on('paises');
$table->index('pais_id' , 'pais_id_fk_idx');

Could you help me?

Thanks in advance.

You can do

public function up()
{
    Schema::create('estados', function (Blueprint $table) {
        $table->bigIncrements('id')->primary('PRIMARY');
        $table->string('nombre' , 30)->unique()->nullable();
        $table->integer('pais_id')->index()->default('1');
        $table->foreign('pais_id')->references('id')->on('paises');
    });
}

you don't need to create manual indexes or foreign keys Laravel will take care of that unless you want to.

From my experience, this is the best way to write it. If your other table is named pais then this will work the best:

public function up()
{
    Schema::create('estados', function (Blueprint $table) {
        $table->id();
        $table->string('nombre' , 30)->nullable()->unique();
        $table->foreignId('pais_id')->constrained();
    });
}

Otherwise, this is good too...

public function up()
{
    Schema::create('estados', function (Blueprint $table) {
        $table->id();
        $table->string('nombre' , 30)->nullable()->unique();
        $table->unsignedBigInteger('pais_id')->default('1');
        $table->foreign('pais_id')->refereces('id')->on('paises');
    });
}

Don't forget to use unsigned() in pais_id

public function up()
{
    Schema::create('estados', function (Blueprint $table) {
        $table->bigIncrements('id')->primary('PRIMARY');
        $table->string('nombre' , 30)->unique()->nullable();
        $table->integer('pais_id')->unsigned()->index()->default('1');
    });
    
    Schema::table('estados', function ($table) {
      $table->foreign('pais_id')->references('id')->on('paises');
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM