简体   繁体   English

在 LARAVEL 5.6 上命名 UNIQUE、INDEX、FOREING KEYS 的正确方法

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

I have this code for my migrations on LARAVEL:我在 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: Idk 如何在同一行中将下 2 行设置为 UNIQUE:

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

Or these 3 lines into only 1 line:或者这 3 行只有 1 行:

$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.除非您愿意,否则您不需要创建手动索引或外键 Laravel 会处理这个问题。

From my experience, this is the best way to write it.根据我的经验,这是最好的写法。 If your other table is named pais then this will work the best:如果您的另一个表名为pais ,那么这将是最好的:

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不要忘记在pais_id中使用unsigned()

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');
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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