企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 数据表创建:`Schema` facade 的 `create` 方法 `create` 方法接收两个参数: 1. 数据表的名称 2. 一个接收 `Blueprint` 实例 `$table` 的闭包,用于定义新数据表。 ~~~php Schema::create('users', function (Blueprint $table) { $table->increments('id'); }); ~~~ >[info] 可以使用数据库结构生成器的任何 [字段方法](database/columns.md) 来定义数据表的字段。 ### 检查数据表或字段是否存在:`Schema` facade 的 `hasTable` 和 `hasColumn` 方法 ~~~php if (Schema::hasTable('users')) { // } if (Schema::hasColumn('users', 'email')) { // } ~~~ ### 指定数据库连接:`Schema` facade 的 `connection` 方法 在非默认的数据库连接 `foo` 中进行数据库结构操作: ~~~php Schema::connection('foo')->create('users', function (Blueprint $table) { $table->increments('id'); }); ~~~ ### 指定数据表属性:在闭包里设置 命令 | 描述 --- | --- `$table->engine = 'InnoDB';` | 设置MySQL数据表的存储引擎。 `$table->charset = 'utf8';` | 设置MySQL数据表的字符集。 `$table->collation = 'utf8_unicode_ci';` | 设置MySQL数据表的排序规则。 ~~~php Schema::create('users', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); }); ~~~ ## 数据表重命名:`Schema` facade 的 `rename` 方法 ~~~php Schema::rename($from, $to); ~~~ ### 重命名带外键的数据表 在重命名前,你需要检查[外键约束](#foreign-key-constraints)涉及到的数据表名,需要在迁移文件中显式的提供, 而不是让 Laravel 按照约定来设置一个名称。因为那样会让外键约束关联到旧的数据表上。 ## 数据表删除:`Schema` facade 的 `drop` 或 `dropIfExists` 方法 ~~~php Schema::drop('users'); Schema::dropIfExists('users'); ~~~ ## 数据表更新:`Schema` facade 的 `table` 方法 如同 `create` 方法,`table` 方法会接收两个参数: 1. 数据表的名称 2. 一个接收 `Blueprint` 实例 `$table` 的闭包,用于更新数据表。 ~~~php Schema::table('users', function (Blueprint $table) { $table->string('email'); }); ~~~ >[info] 可以使用任何数据库结构构造器的 [字段方法](database/columns.md) 来定义数据表的字段。