多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 数据迁移 迁移就像是数据库中的版本控制,它让团队能够轻松的修改跟共享应用程序的数据库结构。新的迁移文件将会被放置在 system/database/migrations 目录中。每个迁移文件的名称都包含了一个时间戳,以便让 hdphp 确认迁移的顺序。 [TOC] ## 迁移指令 ### 新增表 ``` php hd make:migration CreateArticleTable --create=article ``` ### 修改表 ``` php hd make:migration ChangeArticleTable --table=article ``` ### 迁移回滚 ``` php hd migrate:rollback ``` ### 迁移重置 执行迁移重置后将会回滚所有迁移数据。 ``` php hd migrate:reset ``` ### 执行迁移 ``` php hd migrate #或执行以下代码也可 php hd migrate:make ``` ## 操作方法 ### 新增表 新增表是指创建用于构建表的数据迁移文件。 系统将在system/database/migrations 目录中创建文件,文件包括up与down 两个方法,up是执行迁移时运行的方法,down是回滚时执行的方法。 ~~~ Schema::create( 'article', function ( Blueprint $table ) { $table->char('hash', 50)->index('hash')->comment('标识'); $table->char( 'name', 30 )->nullable(); },'这是表注释' ); ~~~ ### 维护表 维护字段指修改已经存在的字段属性或添加一个新的表字段。 系统将在system/database/migrations 目录中创建文件,文件包括up与down 两个方法,up是执行迁移时运行的方法,down是回滚时执行的方法。 文件中添加以下代码用于修改 name 字段长度为50,并添加新字段 about。 ``` Schema::table('users', function (Blueprint $table) { //修改字段 $table->string('name', 50)->change(); //添加字段 $table->string('about', 100)->add(); }); ``` ## 字段类型 | 命令 |描述 | | --- | --- | | $table->increments | 递增 ID(主键) | | $table->text('description') | 相当于 TEXT 型态 | | $table->mediumtext('content') | 相当于 MEDIUMTEXT 型态 | |$table->tinyInteger('numbers')|相当于 TINYINT 型态| |$table->smallint('numbers')|相当于 SMALLINT 型态| |$table->integer('total')| 相当于 INTEGER(INT) 型态| |$table->mediumint('total')| 相当于 MEDIUMINT 型态| |$table->char('name', 30)|相当于 CHAR 型态,并带有长度| |$table->string('email') | 相当于 VARCHAR 型态 | |$table->string('name', 100)|相当于 VARCHAR 型态,并带有长度| |$table->timestamps()|加入 created_at 和 updated_at 字段| |$table->decimal('amount', 5, 2)| DECIMAL 型态,并带有精度与基数| |$table->double('column', 15, 8)|相当于 DOUBLE 型态,总共有 15 位数,在小数点后面有 8 位数| |$table->enum('sex', ['boy', 'girl'])|相当于 ENUM 型态| |$table->float('amount',5,2)|相当于 FLOAT 型态| |$table->date('createtime')|相当于 DATE 型态| |$table->datetime('createtime')|相当于 DATETIME 型态| ## 字段修饰 除了上述的字段类型列表,还有一些其它的字段「修饰」,你可以将它增加到字段中。例如,若要让字段「nullable」,那么你可以使用 nullable 方法: ``` Schema::create( 'article', function ( Blueprint $table ) { $table->char( 'name', 30 )->nullable(); },'这是表注释' ); ``` 以下列表为字段的可用修饰。 | 修饰 | 描述 | | --- | --- | | ->nullable() | 此字段允许写入 NULL 值 | |->defaults($value)|为此字段指定「默认」值| |->comment('注释')|增加注释| |->unsigned()|设置 integer 字段为 UNSIGNED| 使用修饰符的示例如下 ``` Schema::create( 'article', function ( Blueprint $table ) { $table->increments( 'id' ); $table->string( 'title', 100 )->index(); $table->tinyInteger( 'nums' )->unsigned(); $table->char( 'name', 30 )->nullable()->defaults( '后盾网' )->comment( '这是注释' ); $table->timestamps(); },'这是表注释'); ``` ## 创建索引 以下指令只有在创建表时可以使用 | 指令 |说明 | | --- | --- | | $table->string('email')->index() | 创建普通索引 | | $table->string('email')->unique()| 创建字段时直接创建该字段的索引 | 维护表时的索引操作请使用 [数据库组件](http://doc.hdphp.com/215186#_14) 管理索引