laravel迁移文件创建表索引

发布时间:2023-01-10 18:32:23 阅读:1163次

最近在优化数据表

主要是没有加索引

在laravel框架中如何添加索引

执行

php artisan make:migration alter_table_user_shop_add_index_user_id_brand_id

<?php

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

class AlterTableUserShopAddIndexUserIdBrandId extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('user_shop', function (Blueprint $table) {
            $table->index(['user_id', 'brand_id']);
        });
    }

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

然后执行命令

php artisan migrate --path=database/migrations/2023_01_10_181358_alter_table_user_shop_add_index_user_id_brand_id.php

即可为表创建索引hl_organization_user_shop_organization_user_id_brand_id_index

结构构造器支持多种类型的索引。
首先,让我们先来看看一个示例,其指定了字段的值必须是唯一的。你可以简单的在字段定义之后链式调用 unique 方法来创建索引:
$table->string('email')->unique();
此外,你也可以在定义完字段之后创建索引。例如:
$table->unique('email');
你也可以传递一个字段的数组至索引方法来创建复合索引:
$table->index(['account_id', 'created_at']);

可用的索引类型
命令 描述
$table->primary('id'); 加入主键。
$table->primary(['first', 'last']); 加入复合键。
$table->unique('email'); 加入唯一索引。
$table->unique('state', 'my_index_name'); 自定义索引名称。
$table->index('state'); 加入基本索引。

移除索引
若要移除索引,则必须指定索引的名称。Laravel 默认会自动给索引分配合理的名称。其将数据表名称,索引的字段名称,及索引类型简单地连接在了一起。举例如下:
命令 描述
$table->dropPrimary('users_id_primary'); 从「users」数据表移除主键。
$table->dropUnique('users_email_unique'); 从「users」数据表移除唯一索引。
$table->dropIndex('geo_state_index'); 从「geo」数据表移除基本索引。

如果你对 dropIndex 传参索引数组,默认的约定是索引名称由数据库表名字和键名拼接而成:
Schema::table('geo', function ($table) { $table->dropIndex(['state']); // Drops index 'geo_state_index' });

更多查看http://t.zoukankan.com/redirect-p-6215081.html

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:laravel迁移文件创建表索引 出自老鄢博客 | 欢迎分享