Beego framework orm multi-table query

Explain that the following key is to use native sql. The truth beegois ormnot perfect. Personal suggestion is to manually create the database to manipulate the database.

One, one-to-one relationship query

  • 1, Primitive sqlbuilding table

    -- ----------------------------
    --  创建一个用户表
    -- ----------------------------
    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. Define the data model (the data model is written according to the data table)

    // 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. Increase data

    • Borrow ormto insert

      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)
      
    • Use native sqlinsert

      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. Delete data

    • Use beegothe ormDelete

      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()
      
    • Use native sqldelete

      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. Update data

    • Use frames to modify data

      o := orm.NewOrm()
      userId := 1
      o.QueryTable(new(models.User)).Filter("id__exact", userId).Update(orm.Params{
              
              
        "UserName": "张三",
      })
      
    • Native sqlquery

      o := orm.NewOrm()
      userId := 1
      o.Raw(`update user set username=? where id = ?`).SetArgs("张三", userId).Exec()
      
  • 6. Query data (here we did not make foreign key associations in the model, only native sqlqueries can be used )

    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()
    

One-to-many relationship

  • 1. Create an article table

    -- ----------------------------
    --  创建一个文章表
    -- ----------------------------
    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. Query data

    • Return data directly

      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()
      
    • Nested data return

      // 先查询用户表,再去查询文章表
      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()
      

Guess you like

Origin blog.csdn.net/kuangshp128/article/details/109446043