說明,如下重點是使用的是原生
sql
。實話說beego
中的orm
還不完善。我的建議仍是本身手動建立數據庫的方式來操做數據庫。git
一、原生sql
建表github
-- ---------------------------- -- 建立一個用戶表 -- ---------------------------- DROP TABLE IF EXISTS `user`; create table `user`( id int(11) primary key auto_increment comment "主鍵id", username varchar(50) not null unique comment "用戶名", password varchar(100) not null comment "密碼", created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間', updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間', index (username) -- 建立一個普通索引 )ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用戶表'; -- ---------------------------- -- 建立一個用戶信息表 -- ---------------------------- DROP TABLE IF EXISTS `user_info`; create table `user_info`( id int(11) primary key auto_increment comment "主鍵id", mobile varchar(11) not null unique comment "手機號碼", salary decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '薪資', created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間', updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間', user_id int(11) not null comment "關聯用戶表id" )engine=innodb default charset=utf8mb4 comment "用戶擴展表";
二、定義數據模型(數據模型根據數據表來寫)sql
// models/user.go文件 package models import ( "github.com/astaxie/beego/orm" "time" ) type User struct { Id int `json:"id"` // 這個地方要定義下數據庫的字段名稱,UserName匹配數據庫是user_name UserName string `json:"username" orm:"column(username)"` Password string `json:"password"` //beego orm插入數據的時候會帶這個字段,必須加上orm:"-"表示在插入數據的時候忽視這個字段 CreatedAt *time.Time `json:"created_at" orm:"-"` UpdatedAt *time.Time `json:"updated_at" orm:"-"` } //自定義表名(非必須的,可是仍是要寫) func (ctx *User) TableName() string { return "user" } func init() { orm.RegisterModel(new(User)) }
//models/userInfo.go文件 package models import ( "github.com/astaxie/beego/orm" "time" ) type UserInfo struct { Id int `json:"id"` Mobile string `json:"mobile"` Salary float64 `json:"salary" orm:"digits(12);decimals(2);description(薪資)"` CreatedAt *time.Time `json:"created_at" orm:"-"` UpdatedAt *time.Time `json:"updated_at" orm:"-"` // 關聯的外鍵 UserId int `json:"user_id"` } func (ctx *UserInfo) TableName() string { return "user_info" } func init() { orm.RegisterModel(new(UserInfo)) }
三、增長數據數據庫
借用orm
方式來插入json
o := orm.NewOrm() user := models.User{UserName: "admin", Password: "123456"} o.Insert(&user) userInfo := models.UserInfo{Mobile: "110", Salary: 100, UserId: user.Id} o.Insert(&userInfo)
使用原生sql
插入markdown
o := orm.NewOrm() res, err := o.Raw(`insert into user(username, password) values(?,?)`, "admin1", "123456").Exec() if err != nil { fmt.Println("插入數據錯誤", err) } else { userId, err1 := res.LastInsertId() if err1 == nil { // 插入到user_info表中 _, err2 := o.Raw(`insert into user_info(mobile, salary,user_id) values(?,?,?)`, "120", 100, "湖北", userId).Exec() if err2 == nil { fmt.Println("插入成功") } } }
四、刪除數據框架
使用beego
的orm
刪除ide
o := orm.NewOrm() userId := 2 //刪除用戶表 o.QueryTable(new(models.User)).Filter("id__exact", userId).Delete() //若是想連表刪除user_info就寫下面的 o.QueryTable(new(models.UserInfo)).Filter("user_id__exact",userId).Delete()
使用原生sql
刪除測試
o := orm.NewOrm() userId := 2 o.Raw(`delete from user where id =?`).SetArgs(userId).Exec() o.Raw(`delete from user_info where user_id = ?`).SetArgs(userId).Exec()
五、更新數據ui
使用框架來修改數據
o := orm.NewOrm() userId := 1 o.QueryTable(new(models.User)).Filter("id__exact", userId).Update(orm.Params{ "UserName": "張三", })
原生sql
查詢
o := orm.NewOrm() userId := 1 o.Raw(`update user set username=? where id = ?`).SetArgs("張三", userId).Exec()
六、查詢數據(這裏咱們沒在模型裏面作外鍵關聯,只能使用原生sql
查詢)
o := orm.NewOrm() userInfoId := 1 var maps []orm.Params o.Raw(`select userInfo.mobile,user.username, user.password, user.created_at, user.updated_at from user_info as userInfo left join user as user on userInfo.user_id = user.id where userInfo.id = ?`).SetArgs(userInfoId).Values(&maps) fmt.Println(maps, "查詢數據") ctx.Data["json"] = map[string]interface{}{ "code": 0, "message": "測試一對一關聯關係表", "data": maps[0], } ctx.ServeJSON()
一、建立文章表
-- ---------------------------- -- 建立一個文章表 -- ---------------------------- DROP TABLE IF EXISTS `article`; create table `article`( id int(11) primary key auto_increment comment "主鍵id", title varchar(100) not null comment "文章標題", updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間', created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間', user_id int(11) not null comment "關聯用戶表id", index (title) -- 普通索引 )engine=innodb default charset=utf8mb4 comment "文章表";
二、 查詢數據
直接一個返回數據
o := orm.NewOrm() var maps []orm.Params o.Raw(`select user.username, user.created_at, user.updated_at, article.title from user as user left join article as article on user.id = article.user_id`).Values(&maps) fmt.Println(maps, "查詢數據") ctx.Data["json"] = map[string]interface{}{ "code": 0, "message": "測試一對一關聯關係表", "data": maps, } ctx.ServeJSON()
嵌套數據返回
// 先查詢用戶表,再去查詢文章表 o := orm.NewOrm() var maps []orm.Params var maps1 []orm.Params o.Raw(`select * from user`).Values(&maps) for _, item := range maps { // 根據數據去查詢文章 o.Raw(`select * from article where user_id = ?`).SetArgs(item["id"]).Values(&maps1) item["articles"] = maps1 } ctx.Data["json"] = map[string]interface{}{ "code": 0, "message": "測試一對一關聯關係表", "data": maps, } ctx.ServeJSON()