Skip to content

字段标签

VEF Framework 使用 struct tag 来定义字段的数据库映射、JSON 序列化和验证规则。

Bun ORM 标签

基本标签

标签说明示例
bun:"column_name"指定列名bun:"user_name"
bun:",pk"主键bun:"id,pk"
bun:",notnull"非空约束bun:"name,notnull"
bun:",unique"唯一约束bun:"email,unique"
bun:",default:value"默认值bun:"status,default:'active'"
bun:",type:type"指定数据库类型bun:"amount,type:decimal(10,2)"
bun:"-"忽略字段bun:"-"

完整示例

go
type Product struct {
    orm.Model
    
    // Primary key with auto-generated UUID
    Id          string          `bun:"id,pk" json:"id"`
    
    // Required field with unique constraint
    Sku         string          `bun:"sku,notnull,unique" json:"sku"`
    
    // Required field
    Name        string          `bun:"name,notnull" json:"name"`
    
    // Optional field (nullable)
    Description null.String     `bun:"description" json:"description"`
    
    // Decimal type with precision
    Price       decimal.Decimal `bun:"price,notnull,type:decimal(10,2)" json:"price"`
    
    // Integer with default value
    Stock       int             `bun:"stock,notnull,default:0" json:"stock"`
    
    // Boolean with default value
    IsActive    bool            `bun:"is_active,notnull,default:true" json:"isActive"`
    
    // Computed field (not stored in database)
    TotalValue  decimal.Decimal `bun:"-" json:"totalValue,omitempty"`
}

JSON 标签

基本标签

标签说明示例
json:"fieldName"指定 JSON 字段名json:"userName"
json:"-"忽略字段(不序列化)json:"-"
json:",omitempty"空值时省略json:"name,omitempty"
json:",string"数字转字符串json:"id,string"

示例

go
type User struct {
    orm.Model
    
    // Standard JSON field
    Username    string      `bun:"username,notnull" json:"username"`
    
    // Hidden field (not included in JSON response)
    Password    string      `bun:"password,notnull" json:"-"`
    
    // Optional field (omitted when empty)
    Bio         null.String `bun:"bio" json:"bio,omitempty"`
    
    // Numeric ID as string in JSON
    ExternalId  int64       `bun:"external_id" json:"externalId,string"`
}

验证标签

VEF Framework 使用 go-playground/validator 进行数据验证。

常用验证规则

标签说明示例
validate:"required"必填validate:"required"
validate:"omitempty"可选(空值跳过验证)validate:"omitempty,email"
validate:"min=n"最小值/长度validate:"min=6"
validate:"max=n"最大值/长度validate:"max=32"
validate:"len=n"精确长度validate:"len=11"
validate:"email"邮箱格式validate:"email"
validate:"url"URL 格式validate:"url"
validate:"uuid"UUID 格式validate:"uuid"
validate:"alpha"仅字母validate:"alpha"
validate:"alphanum"字母数字validate:"alphanum"
validate:"numeric"数字字符串validate:"numeric"
validate:"oneof=a b c"枚举值validate:"oneof=active inactive"
validate:"eqfield=Field"等于另一字段validate:"eqfield=Password"

验证示例

go
// UserCreateParams defines validation rules for user creation
type UserCreateParams struct {
    api.P
    
    // Required, alphanumeric, 3-32 characters
    Username        string `json:"username" validate:"required,alphanum,min=3,max=32" label:"用户名"`
    
    // Required, valid email format
    Email           string `json:"email" validate:"required,email" label:"邮箱"`
    
    // Required, 6-32 characters
    Password        string `json:"password" validate:"required,min=6,max=32" label:"密码"`
    
    // Required, must equal Password field
    PasswordConfirm string `json:"passwordConfirm" validate:"required,eqfield=Password" label:"确认密码"`
    
    // Optional, max 64 characters
    DisplayName     string `json:"displayName" validate:"omitempty,max=64" label:"显示名称"`
    
    // Optional, valid URL if provided
    Website         string `json:"website" validate:"omitempty,url" label:"网站"`
    
    // Required, must be one of the allowed values
    Role            string `json:"role" validate:"required,oneof=admin user guest" label:"角色"`
}

label 标签

label 标签用于在验证错误消息中显示友好的字段名称:

go
type Params struct {
    Username string `json:"username" validate:"required" label:"用户名"`
}

// Validation error message: "用户名 is required"

搜索标签

搜索标签用于自动构建查询条件,详见 搜索标签

go
type UserSearch struct {
    api.P
    Username string `json:"username" search:"contains"`     // LIKE %value%
    Email    string `json:"email" search:"eq"`              // = value
    Age      int    `json:"age" search:"gte"`               // >= value
    Status   string `json:"status" search:"in"`             // IN (values)
}

关系标签

一对多关系

go
type User struct {
    orm.Model
    Username string  `bun:"username,notnull" json:"username"`
    
    // User has many orders
    Orders   []Order `bun:"rel:has-many,join:id=user_id" json:"orders,omitempty"`
}

type Order struct {
    orm.Model
    UserId string `bun:"user_id,notnull" json:"userId"`
    
    // Order belongs to user
    User   *User  `bun:"rel:belongs-to,join:user_id=id" json:"user,omitempty"`
}

多对多关系

go
type User struct {
    orm.Model
    Username string `bun:"username,notnull" json:"username"`
    
    // Many-to-many through user_roles table
    Roles    []Role `bun:"m2m:user_roles,join:User=Role" json:"roles,omitempty"`
}

组合标签示例

go
type Article struct {
    orm.Model
    
    // Multiple constraints
    Slug        string      `bun:"slug,notnull,unique" json:"slug" validate:"required,alphanum,min=3,max=100"`
    
    // With default value and validation
    Status      string      `bun:"status,notnull,default:'draft'" json:"status" validate:"oneof=draft published archived"`
    
    // Decimal with type specification
    ViewCount   int         `bun:"view_count,notnull,default:0" json:"viewCount"`
    
    // Nullable with omitempty
    PublishedAt null.Time   `bun:"published_at" json:"publishedAt,omitempty"`
    
    // Relation with omitempty
    Author      *User       `bun:"rel:belongs-to,join:author_id=id" json:"author,omitempty"`
    AuthorId    string      `bun:"author_id,notnull" json:"authorId"`
    
    // Computed field (not stored)
    ReadTime    int         `bun:"-" json:"readTime,omitempty"`
}

下一步

基于 Apache License 2.0 许可发布