[TOC]
# 模型定義
復雜的模型定義不是必須的,此功能用作數據庫數據轉換和[自動建表](cmd.md#自動建表)
默認的表名規則,使用駝峰轉蛇形:
AuthUser -> auth_user
Auth_User -> auth__user
DB_AuthUser -> d_b__auth_user
除了開頭的大寫字母以外,遇到大寫會增加 `_`,原名稱中的下劃線保留。
## 自定義表名
```go
type User struct {
Id int
Name string
}
func (u *User) TableName() string {
return "auth_user"
}
```
如果[前綴設置](orm.md#registermodelwithprefix)為`prefix_`那么表名為:prefix_auth_user
## 自定義索引
為單個或多個字段增加索引
```go
type User struct {
Id int
Name string
Email string
}
// 多字段索引
func (u *User) TableIndex() [][]string {
return [][]string{
[]string{"Id", "Name"},
}
}
// 多字段唯一鍵
func (u *User) TableUnique() [][]string {
return [][]string{
[]string{"Name", "Email"},
}
}
```
## 自定義引擎
僅支持 MySQL
默認使用的引擎,為當前數據庫的默認引擎,這個是由你的 mysql 配置參數決定的。
你可以在模型里設置 TableEngine 函數,指定使用的引擎
```go
type User struct {
Id int
Name string
Email string
}
// 設置引擎為 INNODB
func (u *User) TableEngine() string {
return "INNODB"
}
```
## 設置參數
```go
orm:"null;rel(fk)"
```
多個設置間使用 `;` 分隔,設置的值如果是多個,使用 `,` 分隔。
#### 忽略字段
設置 `-` 即可忽略 struct 中的字段
```go
type User struct {
...
AnyField string `orm:"-"`
...
}
```
#### auto
當 Field 類型為 int, int32, int64, uint, uint32, uint64 時,可以設置字段為自增健
* 當模型定義里沒有主鍵時,符合上述類型且名稱為 `Id` 的 Field 將被視為自增健。
鑒于 go 目前的設計,即使使用了 uint64,但你也不能存儲到他的最大值。依然會作為 int64 處理。
參見 issue [6113](http://code.google.com/p/go/issues/detail?id=6113)
#### pk
設置為主鍵,適用于自定義其他類型為主鍵
#### null
數據庫表默認為 `NOT NULL`,設置 null 代表 `ALLOW NULL`
```go
Name string `orm:"null"`
```
#### index
為單個字段增加索引
#### unique
為單個字段增加 unique 鍵
```go
Name string `orm:"unique"`
```
#### column
為字段設置 db 字段的名稱
```go
Name string `orm:"column(user_name)"`
```
#### size
string 類型字段默認為 varchar(255)
設置 size 以后,db type 將使用 varchar(size)
```go
Title string `orm:"size(60)"`
```
#### digits / decimals
設置 float32, float64 類型的浮點精度
```go
Money float64 `orm:"digits(12);decimals(4)"`
```
總長度 12 小數點后 4 位 eg: `99999999.9999`
#### auto_now / auto_now_add
```go
Created time.Time `orm:"auto_now_add;type(datetime)"`
Updated time.Time `orm:"auto_now;type(datetime)"`
```
* auto_now 每次 model 保存時都會對時間自動更新
* auto_now_add 第一次保存時才設置時間
對于批量的 update 此設置是不生效的
#### type
設置為 date 時,time.Time 字段的對應 db 類型使用 date
```go
Created time.Time `orm:"auto_now_add;type(date)"`
```
設置為 datetime 時,time.Time 字段的對應 db 類型使用 datetime
```go
Created time.Time `orm:"auto_now_add;type(datetime)"`
```
#### default
為字段設置默認值,類型必須符合(目前僅用于級聯刪除時的默認值)
```go
type User struct {
...
Status int `orm:"default(1)"`
...
}
```
## 表關系設置
#### rel / reverse
**RelOneToOne**:
```go
type User struct {
...
Profile *Profile `orm:"null;rel(one);on_delete(set_null)"`
...
}
```
對應的反向關系 **RelReverseOne**:
```go
type Profile struct {
...
User *User `orm:"reverse(one)"`
...
}
```
**RelForeignKey**:
```go
type Post struct {
...
User *User `orm:"rel(fk)"` // RelForeignKey relation
...
}
```
對應的反向關系 **RelReverseMany**:
```go
type User struct {
...
Posts []*Post `orm:"reverse(many)"` // fk 的反向關系
...
}
```
**RelManyToMany**:
```go
type Post struct {
...
Tags []*Tag `orm:"rel(m2m)"` // ManyToMany relation
...
}
```
對應的反向關系 **RelReverseMany**:
```go
type Tag struct {
...
Posts []*Post `orm:"reverse(many)"`
...
}
```
#### rel_table / rel_through
此設置針對 `orm:"rel(m2m)"` 的關系字段
rel_table 設置自動生成的 m2m 關系表的名稱
rel_through 如果要在 m2m 關系中使用自定義的 m2m 關系表
通過這個設置其名稱,格式為 pkg.path.ModelName
eg: app.models.PostTagRel
PostTagRel 表需要有到 Post 和 Tag 的關系
當設置 rel_table 時會忽略 rel_through
設置方法:
`orm:"rel(m2m);rel_table(the_table_name)"`
`orm:"rel(m2m);rel_through(pkg.path.ModelName)"`
#### on_delete
設置對應的 rel 關系刪除時,如何處理關系字段。
cascade 級聯刪除(默認值)
set_null 設置為 NULL,需要設置 null = true
set_default 設置為默認值,需要設置 default 值
do_nothing 什么也不做,忽略
```go
type User struct {
...
Profile *Profile `orm:"null;rel(one);on_delete(set_null)"`
...
}
type Profile struct {
...
User *User `orm:"reverse(one)"`
...
}
// 刪除 Profile 時將設置 User.Profile 的數據庫字段為 NULL
```
#### 關于 on_delete 的相關例子
```go
type User struct {
Id int
Name string
}
type Post struct {
Id int
Title string
User *User `orm:"rel(fk)"`
}
```
假設 Post -> User 是 ManyToOne 的關系,也就是外鍵。
o.Filter("Id", 1).Delete()
這個時候即會刪除 Id 為 1 的 User 也會刪除其發布的 Post
不想刪除的話,需要設置 set_null
```go
type Post struct {
Id int
Title string
User *User `orm:"rel(fk);null;on_delete(set_null)"`
}
```
那這個時候,刪除 User 只會把對應的 Post.user_id 設置為 NULL
當然有時候為了高性能的需要,多存點數據無所謂啊,造成批量刪除才是問題。
```go
type Post struct {
Id int
Title string
User *User `orm:"rel(fk);null;on_delete(do_nothing)"`
}
```
那么只要刪除的時候,不操作 Post 就可以了。
## 模型字段與數據庫類型的對應
在此列出 ORM 推薦的對應數據庫類型,自動建表功能也會以此為標準。
默認所有的字段都是 **NOT NULL**
#### MySQL
| go |mysql
| :--- | :---
| int, int32 - 設置 auto 或者名稱為 `Id` 時 | integer AUTO_INCREMENT
| int64 - 設置 auto 或者名稱為 `Id` 時 | bigint AUTO_INCREMENT
| uint, uint32 - 設置 auto 或者名稱為 `Id` 時 | integer unsigned AUTO_INCREMENT
| uint64 - 設置 auto 或者名稱為 `Id` 時 | bigint unsigned AUTO_INCREMENT
| bool | bool
| string - 默認為 size 255 | varchar(size)
| string - 設置 type(text) 時 | longtext
| time.Time - 設置 type 為 date 時 | date
| time.Time | datetime
| byte | tinyint unsigned
| rune | integer
| int | integer
| int8 | tinyint
| int16 | smallint
| int32 | integer
| int64 | bigint
| uint | integer unsigned
| uint8 | tinyint unsigned
| uint16 | smallint unsigned
| uint32 | integer unsigned
| uint64 | bigint unsigned
| float32 | double precision
| float64 | double precision
| float64 - 設置 digits, decimals 時 | numeric(digits, decimals)
#### Sqlite3
| go | sqlite3
| :--- | :---
| int, int32, int64, uint, uint32, uint64 - 設置 auto 或者名稱為 `Id` 時 | integer AUTOINCREMENT
| bool | bool
| string - 默認為 size 255 | varchar(size)
| string - 設置 type(text) 時 | text
| time.Time - 設置 type 為 date 時 | date
| time.Time | datetime
| byte | tinyint unsigned
| rune | integer
| int | integer
| int8 | tinyint
| int16 | smallint
| int32 | integer
| int64 | bigint
| uint | integer unsigned
| uint8 | tinyint unsigned
| uint16 | smallint unsigned
| uint32 | integer unsigned
| uint64 | bigint unsigned
| float32 | real
| float64 | real
| float64 - 設置 digits, decimals 時 | decimal
#### PostgreSQL
| go | postgres
| :--- | :---
| int, int32, int64, uint, uint32, uint64 - 設置 auto 或者名稱為 `Id` 時 | serial
| bool | bool
| string - 默認為 size 255 | varchar(size)
| string - 設置 type(text) 時 | text
| time.Time - 設置 type 為 date 時 | date
| time.Time | timestamp with time zone
| byte | smallint CHECK("column" >= 0 AND "column" <= 255)
| rune | integer
| int | integer
| int8 | smallint CHECK("column" >= -127 AND "column" <= 128)
| int16 | smallint
| int32 | integer
| int64 | bigint
| uint | bigint CHECK("column" >= 0)
| uint8 | smallint CHECK("column" >= 0 AND "column" <= 255)
| uint16 | integer CHECK("column" >= 0)
| uint32 | bigint CHECK("column" >= 0)
| uint64 | bigint CHECK("column" >= 0)
| float32 | double precision
| float64 | double precision
| float64 - 設置 digits, decimals 時 | numeric(digits, decimals)
## 關系型字段
其字段類型取決于對應的主鍵。
* RelForeignKey
* RelOneToOne
* RelManyToMany
* RelReverseOne
* RelReverseMany
- 寫在前面的話
- 第0章 beego 簡介
- 0.1 為beego貢獻
- 0.2 發布版本
- 0.3 升級指南
- 第1章 安裝升級
- 1.1 bee工具的使用
- 第2章 快速入門
- 2.1 新建項目
- 2.2 路由設置
- 2.3 Controller運行機制
- 2.4 Model邏輯
- 2.5 View編寫
- 2.6 靜態文件處理
- 第3章 beego的MVC架構
- 3.1 Model設計
- 3.1.1 概述
- 3.1.2 ORM使用
- 3.1.3 CRUD操作
- 3.1.4 高級查詢
- 3.1.5 原生SQL查詢
- 3.1.6 構造查詢
- 3.1.7 事物處理
- 3.1.8 模型定義
- 3.1.9 命令模式
- 3.1.10 測試用例
- 3.1.11 自定義字段
- 3.1.12 FAQ
- 3.2 View設計
- 3.2.1 模板語法指南
- 3.2.2 模板處理
- 3.2.3 模板函數
- 3.2.4 靜態文件處理
- 3.2.5 模板分頁處理
- 3.3 Controller設計
- 3.3.1 參數配置
- 3.3.2 路由設置
- 3.3.3 控制器函數
- 3.3.4 XSRF過濾
- 3.3.5 請求數據處理
- 3.3.6 session 控制
- 3.3.7 過濾器
- 3.3.8 flash 數據
- 3.3.9 URL構建
- 3.3.10 多種格式數據輸出
- 3.3.11 表單數據驗證
- 3.3.12 錯誤處理
- 3.3.13 日志處理
- 第4章 beego的模塊設計
- 4.1 session 模塊
- 4.2 grace 模塊
- 4.3 cache 模塊
- 4.4 logs 模塊
- 4.5 httplib 模塊
- 4.6 context 模塊
- 4.7 toolbox 模塊
- 4.8 config 模塊
- 4.9 i18n 模塊
- 第5章 beego高級編程
- 5.1 進程內監控
- 5.2 API自動化文檔
- 第6章 應用部署
- 6.1 獨立部署
- 6.2 Supervisor部署
- 6.3 Nginx 部署
- 6.4 Apache 部署
- 第7章 第三方庫
- 第8章 應用例子
- 8.1 在線聊天室
- 8.2 短域名服務
- 8.3 Todo列表
- 第9章 FAQ