thinkPHP使用migrate实现数据库迁移的方法

这篇文章给大家分享的是有关thinkPHP使用migrate实现数据库迁移的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

发展壮大离不开广大客户长期以来的信赖与支持,我们将始终秉承“诚信为本、服务至上”的服务理念,坚持“二合一”的优良服务模式,真诚服务每家企业,认真做好每个细节,不断完善自我,成就企业,实现共赢。行业涉及水泥搅拌车等,在成都网站建设营销型网站建设、WAP手机网站、VI设计、软件开发等项目上具有丰富的设计经验。

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实现数据库迁移的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

名称栏目:thinkPHP使用migrate实现数据库迁移的方法
网站链接:https://www.cdcxhl.com/article26/pocccg.html

成都网站建设公司_创新互联,为您提供Google网站策划微信小程序企业建站移动网站建设静态网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都做网站