【问题标题】:How to index table column of specific database with code in laravel如何在laravel中使用代码索引特定数据库的表列
【发布时间】:2021-10-04 19:55:14
【问题描述】:
我想编写代码来索引特定数据库表列的列。
我正在尝试这种方式
DB::connection('mysql2')->raw("ALTER TABLE `consignments` DROP INDEX customer_reference");
这个过程的正确方法是什么
【问题讨论】:
标签:
laravel
eloquent
laravel-8
laravel-query-builder
【解决方案1】:
您需要使用 Laravel 迁移,请参阅此文档:
Laravel Migrations
Laravel Migrations/Index related
您可以在项目路径的shell中执行此命令,并在数据库/迁移路径中编辑创建的文件,并为文档后面的列添加索引
php artisan make:migration add_index_to_consignments_table
或者在数据库/迁移路径中手动创建一个文件,名称如下:
2021_07_29_022532_add_index_to_consignments_table.php 并复制/粘贴此 php 内容
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddIndexToConsignmentsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('consignments', function (Blueprint $table) {
//Uncomment one line depending on what you need
//$table->index('customer_reference'); //If you need to add an index
//$table->dropIndex('name_of_index_on_table'); //If you need to remove an index
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::table('consignments', function (Blueprint $table) {
//Uncomment one line depending on what you need
//$table->dropIndex('name_of_index_on_table'); //If you need to add an index
//$table->index('customer_reference'); //If you need to remove an index
});
}
}
使用任何方法创建文件后,您必须在项目路径上的 shell 中执行此命令:
php artisan migrate