说明,如下重点是使用的是原生
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()