gorm操练记录
2024-09-06 14:12:24
这个数据库的定义蛮全的,先作个记录。
package main import ( "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type User struct { gorm.Model Birthday time.Time Age int Name string `gorm:"size:255"` // string默认长度为255, 使用这种tag重设。 Num int `gorm:"AUTO_INCREMENT"` // 自增 CreditCard CreditCard // One-To-One (拥有一个 - CreditCard表的UserID作外键) Emails []Email // One-To-Many (拥有多个 - Email表的UserID作外键) BillingAddress Address // One-To-One (属于 - 本表的BillingAddressID作外键) //BillingAddressID sql.NullInt64 ShippingAddress Address // One-To-One (属于 - 本表的ShippingAddressID作外键) ShippingAddressID int IgnoreMe int `gorm:"-"` // 忽略这个字段 Languages []Language `gorm:"many2many:user_languages;"` // Many-To-Many , 'user_languages'是连接表 } type Email struct { ID int UserID int `gorm:"index"` // 外键 (属于), tag `index`是为该列创建索引 Email string `gorm:"type:varchar(100);unique_index"` // `type`设置sql类型, `unique_index` 为该列设置唯一索引 Subscribed bool } type Address struct { ID int Address1 string `gorm:"not null;unique"` // 设置字段为非空并唯一 Address2 string `gorm:"type:varchar(100);unique"` //Post sql.NullString `gorm:"not null"` } type Language struct { ID int Name string `gorm:"index:idx_name_code"` // 创建索引并命名,如果找到其他相同名称的索引则创建组合索引 Code string `gorm:"index:idx_name_code"` // `unique_index` also works } type CreditCard struct { gorm.Model UserID uint Number string } func main() { db, err := gorm.Open("mysql", "root:password@(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local") if err != nil { panic(err) } db.DB().SetMaxIdleConns(10) db.DB().SetMaxOpenConns(100) db.SingularTable(true) defer db.Close() // 自动迁移模式 db.AutoMigrate(&User{}, &Email{}, &Address{}, &Language{}, &CreditCard{}) /* db.Create(&Product{Code: "L1212", Price: 1000}) // 读取 var product Product db.First(&product, 1) // 查询id为1的product db.First(&product, "code = ?", "L1212") // 查询code为l1212的product // 更新 - 更新product的price为2000 db.Model(&product).Update("Price", 2000) // 删除 - 删除product db.Delete(&product) tx := db.Begin() r1 := db.DropTable(&Address{}) r2 := db.DropTableIfExists(&CreditCard{}) if r1.Error != nil || r2.Error != nil { tx.Rollback() return } tx.Commit() */ }
最新文章
- 隐藏自定义tabbar(关于tabbar的hide属性对于自定义无效)
- SQL Server中常用的SQL语句
- 007. 自定义ListBox的item的宽高, 字体居中
- hdu 2486/2580 / poj 3922 A simple stone game 博弈论
- POJ-2386(深广搜基础)
- ADO.Net对Oracle数据库的操作【转载】
- asp.net、html、javascript等比较有用的网站
- MUI开发注意事项
- MySQL 5.7中 performance_schema 替代 show profile 命令
- Android studio 一些技术添加依赖,依赖库
- android+eclipse+mysql+servlet(Android与mysql建立链接)
- 数组的toString方法
- vue 首页问题
- mybatis配置文件配错
- 【读书笔记】iOS-加速计与陀螺仪
- Spring Security 指定登陆入口
- CSS-background-position百分比
- Nginx是如何配置为 Web 服务器的【转载】
- npm汇总:npm命令 + 实用插件
- npm run dev启动项目报错 Cannot find module 'webpack-cli/bin/config-yargs'