beego框架orm多表查询

说明,以下重点是使用的是原生sql。实话说beego中的orm还不完善。个人建议还是自己手动创建数据库的方式来操作数据库。

一、一对一关系查询

  • 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、删除数据

    • 使用beegoorm删除

      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、创建文章表

    -- ----------------------------
    --  创建一个文章表
    -- ----------------------------
    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()
      

版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/kuangshp128/article/details/109446043