# 數據庫migration的使用改造-字段
用到的類庫
```php
use ClassLibrary\ClMigrateField;
```
回滾上次的數據庫修改
```php
php think migrate:rollback
```
接著修改user migration 文檔,新增一個name字段和密碼
```php
<?php
use think\migration\Migrator;
use think\migration\db\Column;
use ClassLibrary\ClMigrateTable;
use ClassLibrary\ClMigrateField;
class User extends Migrator
{
public function up()
{
$table = 'user';
if($this->hasTable($table)){
return;
}
$this->table($table)
->setComment(
ClMigrateTable::instance()
->fetch('用戶表')
)
->addColumn('name', 'string', ['default' => '', 'comment' =>
ClMigrateField::instance()
//必填
->verifyIsRequire()
//中文
->verifyChinese()
->fetch('名稱')
])
->addColumn('password', 'string', ['default' => '', 'comment' =>
ClMigrateField::instance()
//必填
->verifyIsRequire()
//密碼格式校驗
->verifyIsPassword()
//存儲為密碼格式,且加密時加上'aaa'
->storageFormatPassword('aaa')
->fetch('密碼')
])
->create();
}
public function down()
{
parent::down();
$table = 'user';
if($this->hasTable($table)){
$this->dropTable($table);
}
}
}
```
執行migrate
```php
php think migrate:run
```
此時的DDL
```sql
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '' COMMENT '{"verifies":["is_required","chinese"],"name":"名稱"}',
`password` varchar(255) NOT NULL DEFAULT '' COMMENT '{"verifies":["is_required",["password",6,18]],"store_format":["password","aaa"],"name":"密碼"}',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='{"name":"用戶表","create_api":["getList","get","create","delete","update"]}';
```
### ClMigrateField函數說明
函數名 | 注釋
---|---
instance | 獲取實例對象
fetch | 獲取表Comment定義Json
invisible | 比如密碼等敏感字段,接口輸出的時候自動過濾掉
isReadOnly | 只讀字段,不可修改
constValues | 定義字段靜態變量,用int類型代替枚舉類型,會自動在model中自動生成對應關系
showMapFields | 映射其他表字段,主鍵id自動映射,不需要關聯查詢
showFormat | 字段格式
storageFormatJson | 字段存儲類型為json,會自動存儲和解析
storageFormatPassword | 存儲格式為密碼,可設置salt,無需手工再md5等方式處理,解決了,多個地方判斷密碼正確性的問題
verifyIsRequire | 校驗,必填字段
verifyIsPassword | 校驗,密碼格式
verifyInArray | 校驗,在數組內
verifyIntInScope | 校驗,在范圍內
verifyIntMax | 校驗,最大int值
verifyIntMin | 校驗,最小int值
verifyStringLength | 校驗,字符串長度
verifyStringLengthMax | 校驗,最大字符串長度
verifyStringLengthMin | 校驗,最小字符串長度
verifyEmail | 校驗,email格式
verifyMobile | 校驗,手機格式
verifyIp | 校驗,ip
verifyPostcode | 校驗,郵編
verifyIdCard | 校驗,身份證
verifyChinese | 校驗,漢字
verifyChineseAlpha | 校驗,漢字+字母
verifyChineseAlphaNum | 校驗,漢字+字母+數字
verifyChineseAlphaNumDash | 校驗,漢字+字母+數字+下劃線_+破折號-
verifyAlpha | 校驗,字母
verifyAlphaNum | 校驗,字母+數字
verifyAlphaNumDash | 校驗,字母+數字+下劃線_+破折號-
verifyUrl | 校驗,網址
verifyNumber | 校驗,數字
verifyArray | 校驗,數組
verifyTel | 校驗,固話
verifyIsDate | 校驗,時間格式
verifyUnique | 校驗,唯一值,比如身份證號、手機號等
### 自動完成字段
如果字段名稱定義為create_time、update_time,程序會自動補充對應的值,會以timestamp時間戳方式填充。