天天看點

Beego Models之四模型定義

模型定義

使用orm定義,然後使用cmd方式,自動建表,不過在實際生産中還是直接使用sql操作的,這種模型定義在生産環境中定義的比較少,基本上都是直接使用基本類型,一些特殊的,都是在資料庫中定義的。

複雜的模型定義不是必須的,此功能用作資料庫資料轉換和

自動建表

預設的表名規則,使用駝峰轉蛇形:

AuthUser -> auth_user
Auth_User -> auth__user
DB_AuthUser -> d_b__auth_user
           

除了開頭的大寫字母以外,遇到大寫會增加

_

,原名稱中的下劃線保留。

自定義表名

type User struct {
    Id int
    Name string
}

func (u *User) TableName() string {
    return "auth_user"
}
           

如果

字首設定

prefix_

那麼表名為:prefix_auth_user

自定義索引

為單個或多個字段增加索引

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 函數,指定使用的引擎

type User struct {
    Id    int
    Name  string
    Email string
}

// 設定引擎為 INNODB
func (u *User) TableEngine() string {
    return "INNODB"
}
           

設定參數

orm:"null;rel(fk)"
           

多個設定間使用

;

分隔,設定的值如果是多個,使用

,

分隔。

忽略字段

設定

-

即可忽略 struct 中的字段

type User struct {
...
    AnyField string `orm:"-"`
...
}
           

auto

當 Field 類型為 int, int32, int64, uint, uint32, uint64 時,可以設定字段為自增健

  • 當模型定義裡沒有主鍵時,符合上述類型且名稱為

    Id

    的 Field 将被視為自增健。

鑒于 go 目前的設計,即使使用了 uint64,但你也不能存儲到他的最大值。依然會作為 int64 處理。

參見 issue

6113

pk

設定為主鍵,适用于自定義其他類型為主鍵

null

資料庫表預設為

NOT NULL

,設定 null 代表

ALLOW NULL

Name string `orm:"null"`
           

index

為單個字段增加索引

unique

為單個字段增加 unique 鍵

Name string `orm:"unique"`
           

column

為字段設定 db 字段的名稱

Name string `orm:"column(user_name)"`
           

size

string 類型字段預設為 varchar(255)

設定 size 以後,db type 将使用 varchar(size)

Title string `orm:"size(60)"`
           

digits / decimals

設定 float32, float64 類型的浮點精度

Money float64 `orm:"digits(12);decimals(4)"`
           

總長度 12 小數點後 4 位 eg:

99999999.9999

auto_now / auto_now_add

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

Created time.Time `orm:"auto_now_add;type(date)"`
           

設定為 datetime 時,time.Time 字段的對應 db 類型使用 datetime

Created time.Time `orm:"auto_now_add;type(datetime)"`
           

default

為字段設定預設值,類型必須符合(目前僅用于級聯删除時的預設值)

type User struct {
    ...
    Status int `orm:"default(1)"`
    ...
}
           

表關系設定

rel / reverse

RelOneToOne:

type User struct {
    ...
    Profile *Profile `orm:"null;rel(one);on_delete(set_null)"`
    ...
}
           

對應的反向關系 RelReverseOne:

type Profile struct {
    ...
    User *User `orm:"reverse(one)"`
    ...
}
           

RelForeignKey:

type Post struct {
    ...
    User *User `orm:"rel(fk)"` // RelForeignKey relation
    ...
}
           

對應的反向關系 RelReverseMany:

type User struct {
    ...
    Posts []*Post `orm:"reverse(many)"` // fk 的反向關系
    ...
}
           

RelManyToMany:

type Post struct {
    ...
    Tags []*Tag `orm:"rel(m2m)"` // ManyToMany relation
    ...
}
           
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     什麼也不做,忽略
           
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 的相關例子

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

type Post struct {
    Id int
    Title string
    User *User `orm:"rel(fk);null;on_delete(set_null)"`
}
           

那這個時候,删除 User 隻會把對應的 Post.user_id 設定為 NULL

當然有時候為了高性能的需要,多存點資料無所謂啊,造成批量删除才是問題。

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
string - 預設為 size 255 varchar(size)
string - 設定 type(char) 時 char(size)
string - 設定 type(text) 時 longtext
time.Time - 設定 type 為 date 時 date
time.Time datetime
byte tinyint unsigned
rune integer
int
int8 tinyint
int16 smallint
int32
int64 bigint
uint integer unsigned
uint8
uint16 smallint unsigned
uint32
uint64 bigint unsigned
float32 double precision
float64
float64 - 設定 digits, decimals 時 numeric(digits, decimals)

Sqlite3

sqlite3
int, int32, int64, uint, uint32, uint64 - 設定 auto 或者名稱為

Id

integer AUTOINCREMENT
character(size)
text
real
decimal

PostgreSQL

postgres

Id

serial
string - 若沒有指定 size 預設為 text
string - 設定 type(json) 時 json
string - 設定 type(jsonb) 時 jsonb
timestamp with time zone
smallint CHECK(“column” >= 0 AND “column” <= 255)
smallint CHECK(“column” >= -127 AND “column” <= 128)
bigint CHECK(“column” >= 0)
integer CHECK(“column” >= 0)

關系型字段

其字段類型取決于對應的主鍵。

  • RelForeignKey
  • RelOneToOne
  • RelManyToMany
  • RelReverseOne
  • RelReverseMany