我是 Laravel 的新手,我知道添加索引会加快查询速度。然而,我对 Laravel 迁移有点困惑。这是代码
Schema::create('affiliate_clients', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(Affiliate::class,'affiliate_id')->constrained('affiliates')->cascadeOnDelete()->cascadeOnUpdate();
$table->foreignIdFor(User::class,'user_id')->unique()->constrained('users')->cascadeOnDelete()->cascadeOnUpdate();
$table->string('token',50);
$table->timestamp('expired_at');
$table->timestamps();
$table->index(['affiliate_id','user_id','token','expired_at','created_at','updated_at']);
});
从上面的代码来看。每个foreignIdFor之间已经存在关系。我应该重复使用 ->index() 吗? (affiliate_id,user_id) 因为它已经在外键中使用了。
在 Laravel 迁移中,当您使用
foreignIdFor
方法结合 constrained
方法定义外键时,Laravel 会自动为这些外键创建索引。因此,您不需要再次显式地为这些列添加索引。
在迁移中,您已经为
affiliate_id
和 user_id
列定义了外键,因此不需要单独为它们添加索引。但是,如果您有在查询中经常使用的其他列,例如 token
、expired_at
或时间戳列(created_at
和 updated_at
),最好为它们添加索引以优化查询性能。
因此,就您而言,您已经正确完成了所有操作。您不需要为
affiliate_id
和 user_id
添加单独的索引,因为它们已经被外键覆盖。但是,为查询中经常使用的其他列(例如 token
、expired_at
、created_at
和 updated_at
)添加索引是个好主意。