公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

ThinkPHP如何使用migrate实现数据库迁移


thinkPHP使用migrate实现数据库迁移

thinkPHP的数据库迁移工具:topthink/think-migration

一:安装topthink/think-migration

这里注意你安装topthink/think-migration时需要注意你的thinkPHP版本,这里我的thinkPHP版本为5.1,所以可以安装topthink/think-migration的2.0版本,无法安装3.0版本,选择你适合的版本进行安装

composer require topthink/think-migration=2.0.*

安装完成之后在命令行执行:

php think

如下表示migrate安装成功

ThinkPHP如何使用migrate实现数据库迁移

二:使用topthink/think-migration实现数据库迁移

1:创建迁移类

在命令行执行

php think migrate:create CreateUser

执行完成之后我们就和在./database/migrateions目录下创建一个migrate迁移文件

ThinkPHP如何使用migrate实现数据库迁移

2:实现数据库迁移

migrate方法使用文档:http://docs.phinx.org/en/latest/migrations.html

[1]:migrate代码说明:

在migrate中有三个方法

up:在migrate:run时执行(前提是文件中不存在change方法)

down:在migrate:rollback时执行(前提是文件中不存在change方法)

change:migrate:run 和migrate:rollback时执行 (如果存在该方法 则不会去执行up 与down)

一般情况下我一般将migrate文件中的change方法删除,up方法专门放置新增和更新表的操作,down方法放置删除表和删除字段操作

(1)新增表:

// create the table
$table = $this->table('user', ['id' => 'user_id', 'comment' => '用户表', 'engine' => 'MyISAM', '']);
$table->addColumn('user_name', 'string', ['limit' => 15, 'default' => '', 'comment' => '用户名'])
    ->addColumn('password', 'string', ['limit' => 15, 'default' => '', 'comment' => '密码',])
    ->addColumn('status', 'boolean', ['limit' => 1, 'default' => 0, 'comment' => '状态'])
    ->addIndex(['user_name'], ['unique' => true])//为user_name创建索引并设置唯一(唯一索引)
    ->addTimestamps()//默认生成create_time和update_time两个字段
    ->create();

(2)更新表:

$this->table('user')
    ->addColumn('test', 'string', ['limit' => 15, 'default' => '', 'comment' => '测试'])//在user表中增加一个test字段

    ->update();

(3)删除表:

$this->table('user')->drop();

(4)删除字段

$this->table('user')
    ->removeColumn('test')//删除user表中的test字段
    ->save();

[2]:migrate命令:

migrate常用的命令有三个,分别为:

php think migrate:create CreateUser  #创建一个迁移类
php think migrate:run  #执行迁移
php think migrate:rollback #迁移回滚



分享到:
标签:ThinkPHP migrate 数据库迁移
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定