本篇文章跟大家分享關於PHP處理中資料庫遷移工具Phinx的相關知識,phinx特別適合在開發、測試、線上資料庫同步欄位資訊、資料資訊、產生和同步測試數據等等,希望對大家有幫助。
文件位址:https://tsy12321.gitbooks.io/phinx-doc/content
##1.安裝
composer require nhzex/think-phinx
2.執行
php vendor/bin/phinx
3.使用phinx.php進行設定
<?php $config = array( 'DB_HOST' => 'localhost', 'DB_NAME' => 'root', 'DB_USER' => 'root', 'DB_PWD' => '', ); $settings = $config; #phinx.php <?php require 'db_config.php'; return array( "paths" => array( "migrations" => "db/migrations", "seeds" => "db/seeds" ), "environments" => array( "defaut_migration_table" => "phinxlog", "default_database" => "lleg", "default_environment" => "development" "production" => array( "adapter" => "mysql", "host" => $settings["DB_HOST"], "name" => $settings["DB_NAME"], "user" => $settings["DB_USER"], "pass" => $settings["DB_PWD"], "port" => 3306, "charset" => "utf8" ), "development" => array( "adapter" => "mysql", "host" => $settings["DB_HOST"], "name" => $settings["DB_NAME"], "user" => $settings["DB_USER"], "pass" => $settings["DB_PWD"], "port" => 3306, "charset" => "utf8" ) ) );
4.執行php vendor/bin/phinx status查看連線狀態
5.執行php vendor/bin/phinx create migration
6.現在生成了created /db/migrations/20180310020523_migration.php
編輯這個檔案,新增資料庫建立內容.public function change() { $user = $this->table('user'); $user->addColumn('open_id', 'string', ['limit'=>64]); $user->addColumn('register_time', 'timestamp', ['default' => 'CURRENT_TIMESTAMP']); $user->addColumn('favorite_music', 'integer', ['default'=> 0, 'comment'=>'喜欢的音乐']); $user->addColumn('favorite_vedio', 'integer', ['default'=> 0, 'comment'=>'喜欢的视频数']); $user->addColumn('favorite_article', 'integer', ['default'=> 0, 'comment'=>'喜欢的文章数']); $user->addColumn('baby_birthday', 'date', ['null'=>true, 'comment'=>'宝宝生日']); $user->addColumn('baby_sex', 'boolean', ['null'=>true, 'comment'=>'宝宝性别']); $user->addColumn('last_login', 'datetime', ['null'=>true, 'comment'=>'最后登陆日期']); $user->save(); }
7.預設會加入一個自增id,作為主鍵
執行php vendor/bin/phinx migrate8.初始化資料
執行php vendor/bin/phinx seed:create CategorySeeder系統自動建立created ./db/seeds/CategorySeeder.php9.修改CategorySeeder.php
執行php vendor/bin/phinx seed:run 將會進行所有Seed10.如果想運行指定的Seed需要用- s參數指定
php vendor/bin/phinx seed:run -s CategorySeeder11.更新表結構
當需要更新表格結構的時候,需要再建立一個migrate執行php vendor/bin/phinx create ChangeArtist#再將需要更新的內容寫到change函數public function change() { $this->execute('alter table resource drop column artist ;'); $resource = $this->table('resource'); $resource->addColumn('artist', 'string', ['limit'=>128, 'default'=>'']); $resource->update(); }
12.回滾
php vendor/bin/phinx rollback
13.資料填入
php vendor/bin/phinx seed:create UserSeeder php vendor/bin/phinx seed:run -e product
<?php use Phinx\Seed\AbstractSeed; class UserSeeder extends AbstractSeed { /** * 插入数据 */ public function run() { $data = array( array( 'id' => 1, ), array( 'id' => 2, ) ); $posts = $this->table('users'); $posts->insert($data)->save(); } }
PHP影片教學》
以上是教你使用PHP資料庫遷移工具'Phinx”的詳細內容。更多資訊請關注PHP中文網其他相關文章!