多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 索引创建 ### 创建唯一索引 1. 在字段定义后,链式调用 `unique` 方法来创建索引: ~~~php $table->string('email')->unique(); ~~~ 2. 也可以在定义完所有字段之后,单独创建索引: ~~~php $table->unique('email'); ~~~ ### 创建复合索引 传递一个包含字段名的数组至索引方法: ~~~php $table->index(['account_id', 'created_at']); ~~~ ### 自定义索引名称 Laravel 会自动生成一个合理的索引名称,但也可以使用第二个参数来自定义: ~~~php $table->index('email', 'my_index_name'); ~~~ ### 可用的索引类型 命令 | 描述 ------------- | ------------- `$table->primary('id');` | 添加主键。 `$table->primary(['first', 'last']);` | 添加复合键。 `$table->unique('email');` | 添加唯一索引。 `$table->unique('state', 'my_index_name');` | 自定义索引名称。 `$table->unique(['first', 'last']);` | 添加复合唯一键。 `$table->index('state');` | 添加基本索引。 ### 配置索引长度 Laravel 默认使用 `utf8mb4` 字符,可支持在数据库里存储「表情」。 如果你使用的 **MySQL 版本低于 5.7.7** 或 **MariaDB 版本低于 10.2.2**,你可能需要手动配置默认字符串长度,以顺利创建索引。 方法是修改 `app/Providers/AppServiceProvider.php` 文件,调用 `Schema::defaultStringLength` 方法: ~~~php use Illuminate\Support\Facades\Schema; /** * Bootstrap any application services. * 引导任何应用程序服务。 * * @return void */ public function boot() { Schema::defaultStringLength(191); } ~~~ 或者你可以为数据库开启 `innodb_large_prefix` 选项,有关如何正确开启此选项的说明请查阅数据库文档。 ## 索引移除 >[danger] 若要移除索引,则**必须**指定索引的名称。 ### 传递完整的索引名称字符串 >[info] Laravel 默认会自动给索引分配合理的名称:数据表名称_索引的字段名称_索引类型。 命令 | 描述 ------------- | ------------- `$table->dropPrimary('users_id_primary');` | 从「users」数据表移除主键。 `$table->dropUnique('users_email_unique');` | 从「users」数据表移除唯一索引。 `$table->dropIndex('geo_state_index');` | 从「geo」数据表移除基本索引。 ### 传递包含字段名的数组 >[info] 索引名称将由 数据表名 和 字段名 拼接而成 ~~~php Schema::table('geo', function (Blueprint $table) { $table->dropIndex(['state']); // 移除索引 'geo_state_index' }); ~~~ ## 外键约束 ### 创建外键约束 有 `user_id` 字段的 `posts` 数据表,`user_id` 引用了 `users` 数据表的 `id` 字段: ~~~php Schema::table('posts', function (Blueprint $table) { $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); }); ~~~ ### 指定外键约束的「on delete」及「on update」行为 ~~~php $table->foreign('user_id') ->references('id')->on('users') ->onDelete('cascade'); ~~~ ### 移除外键约束: `dropForeign` 方法 #### 传递完整的外键约束名称字符串 >[info] 外键约束与索引采用相同的命名方式:数据表名称_约束字段_foreign。 ~~~php $table->dropForeign('posts_user_id_foreign'); ~~~ #### 传递一个包含字段名的数组 ~~~php $table->dropForeign(['user_id']); ~~~ > 在移除的时候,字段会按照惯例被自动转换为对应的外键名称。 #### 在迁移文件里开启和关闭外键约束 ~~~php // 开启 Schema::enableForeignKeyConstraints(); // 关闭 Schema::disableForeignKeyConstraints(); ~~~