laravel 5-如何向现有外键添加-> index()

Dan*_*nai 3 php mysql sql laravel laravel-5

框架:Laravel 5.2数据库:MySQL PHP:7.0

我有表“ poptins”:

    Schema::create('poptins', function (Blueprint $table) {
        $table->string('id')->primary()->index();
        $table->string('ab_test_parent_id')->nullable();
        $table->string('cloned_parent_id')->nullable();
        $table->timestamps();
    });
Run Code Online (Sandbox Code Playgroud)

和表“转换”:

    Schema::create('conversions', function (Blueprint $table) {
        $table->string('id')->primary()->index();
        $table->integer('users')->default(null);
        $table->string('name',256)->default(null);
        $table->string('poptin_id');
        $table->foreign('poptin_id')->references('id')->on('poptins')->onDelete('cascade')->onUpdate('cascade');
        $table->timestamps();
    });
Run Code Online (Sandbox Code Playgroud)

我在“转换”表中设置了外键(poptin_id)。现在是否意味着外键(poptin_id)也是索引?如果不是...我需要做些什么才能使其成为索引?

谢谢?

che*_*aby 5

您可以做到这一点。

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddIndexToLeads extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('leads', function(Blueprint $table)
        {
            $table->index('trader_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('leads', function (Blueprint $table)
        {
            $table->dropIndex(['trader_id']);
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

归功于@bobbybouwmann


Vip*_*pro 5

我刚写的时候遇到了问题:-

$table->index('column_name');
Run Code Online (Sandbox Code Playgroud)

因此,更准确地说,首先您需要创建具有所需列类型的列,然后将其分配为索引,如下所示:-

  $table->string('column_name');
  $table->index('column_name');
  //or
  $table->string('column_name')->index();
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助


zar*_*pio 5

这里为您提供完美的解决方案。

向上

$table->string('poptin_id')->index('poptin_id');
Run Code Online (Sandbox Code Playgroud)

向下

$table->dropIndex(['poptin_id']);
Run Code Online (Sandbox Code Playgroud)

修复迁移的建议

$table->string('id')->primary()->index();
Run Code Online (Sandbox Code Playgroud)

将上面替换为下面

$table->increments('id');
Run Code Online (Sandbox Code Playgroud)

并按如下方式修复您的外键

$table->integer('poptin_id')->index('poptin_id')->unsigned();
Run Code Online (Sandbox Code Playgroud)


San*_*esh 4

Laravel 只添加外键约束,并不隐式添加索引。但有些数据库(例如 MySQL)会自动索引外键列。

如果您需要在另一个迁移中为某个字段添加索引。那么你可以做

$table->index('email');
Run Code Online (Sandbox Code Playgroud)