在Laravel(v6.8(中,我为users
表创建了以下迁移。
用户迁移
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username')->unique()->index();
$table->string('email')->unique()->index();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
$table->boolean('is_root')->default(FALSE);
$table->rememberToken();
$table->timestamps();
$table->unique(['username', 'email'], 'user_unique_credentials');
$table->index(['username', 'email'], 'user_index_columns');
});
}
解释
我知道index
的基本知识及其工作原理,但我对index
在单个column
和composite/compound
index
上的理解不太清楚。
应用程序可能仅通过username
或email
进行查询,或者我可能同时对两个表进行查询。因此,正如您在我的迁移代码中看到的那样,我已经为每一列以及两列设置了index
,并使用$this->index()
创建了compound
index
。
问题
我想知道我是否已经正确设置了所有
indexes
,或者按照我的方式设置是个坏主意?如果不正确,我可以知道正确的方法吗
@danblack感谢您的帮助。
好吧,最后尝试以各种方式设置unique
和index
的EXPLAIN
查询,我找到了如下的最终版本。
public function up()
{
Schema::create(
'users',
function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->enum('role', ['super', 'admin', 'manager', 'subscriber', 'user'])->default('user');
$table->boolean('is_root')->default(FALSE);
$table->rememberToken();
$table->timestamps();
$table->unique(['username', 'email'], 'users_unique_credentials');
}
);
}
这样,当我们查询单个列时,它将使用自己的唯一索引。当我们使用具有多个WHERE
子句的两列进行搜索时,它将使用compound
unique
索引。