Метод index
Метод index класса Blueprint применяется для создания
обычного (неуникального) индекса в таблице базы данных.
Он принимает первым параметром массив имён колонок или одну
колонку в виде строки, вторым параметром - имя индекса,
которое может быть опущено (тогда Laravel сгенерирует его
автоматически). Индексы значительно ускоряют выполнение
запросов с условиями WHERE и операциями ORDER BY.
Синтаксис
<?php
Schema::create('table', function (Blueprint $table) {
$table->index($columns, $name);
});
?>
Пример
Давайте создадим индекс для одной колонки 'email'
в таблице пользователей:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();
$table->index('email');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
?>
Пример
Давайте создадим составной индекс для нескольких колонок
'first_name' и 'last_name':
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration
{
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->index(['first_name', 'last_name']);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('employees');
}
}
?>
Пример
Давайте создадим индекс с произвольным именем для колонки
'phone':
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContactsTable extends Migration
{
public function up()
{
Schema::create('contacts', function (Blueprint $table) {
$table->id();
$table->string('phone');
$table->index('phone', 'phone_index_custom');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('contacts');
}
}
?>
Пример
Давайте создадим индекс с указанием типа индекса для
колонки 'status':
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOrdersTable extends Migration
{
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('status');
$table->integer('amount');
$table->index('status');
$table->index('amount');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('orders');
}
}
?>