次のキーはネイティブを使用することであることを説明します
sql
。真実beego
はorm
完璧ではありません。個人的な提案は、データベースを手動で作成してデータベースを操作することです。
1対1の関係クエリ
-
1、原生
sql
建表-- ---------------------------- -- 创建一个用户表 -- ---------------------------- 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 "用户扩展表";
-
2.データモデルを定義します(データモデルはデータテーブルに従って記述されます)
// 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)) }
-
3.データを増やす
-
orm
挿入するために借りる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
インサートを使用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("插入成功") } } }
-
-
4.データを削除します
-
削除を使用
beego
するorm
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()
-
-
5.データを更新します
-
フレームを使用してデータを変更する
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()
-
-
6.データのクエリ(ここでは、モデルで外部キーの関連付けを行いませんでした。ネイティブ
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()
1対多の関係
-
1.記事テーブルを作成します
-- ---------------------------- -- 创建一个文章表 -- ---------------------------- 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 "文章表";
-
2.クエリデータ
-
データを直接返す
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()
-