Beego framework orm basic use one

1. Basic configuration

  • 1. Install dependencies

    // orm链接库
    go get github.com/astaxie/beego/orm
    // 使用的数据库
    go get github.com/go-sql-driver/mysql
    
  • 2. main.goAdd a initmethod to the file to connect to the database

    func init()  {
          
          
    	orm.RegisterDriver("mysql", orm.DRMySQL)
      // default必须要有,表示连接的数据库别名,可能是多个
    	orm.RegisterDataBase("default", "mysql", "用户名:密码@tcp(localhost:3306)/数据库名?charset=utf8mb4&parseTime=True&loc=Local")
    }
    
  • 3. Note that main.gosuch a package must be added to the file, otherwise an error will be reported

    import (
    	...
    	_ "github.com/go-sql-driver/mysql"
    )
    
  • 4. Define a data model

    package models
    
    import "github.com/astaxie/beego/orm"
    
    type User struct {
          
          
    	Id int
    	Name string
    	Age int
    	Address string
    }
    
    //自定义表名,可以不写的会默认以下划线来分割驼峰命名的
    func (self *User) TableName () string  {
          
          
    	return "user"
    }
    
    func init() {
          
          
    	orm.RegisterModel(new(User))
    }
    
  • 5. Manually create a database and userdata table

  • 6. Use the data model in the controller to insert data

    package ormDemo
    
    import (
    	"demo01/models"
    	"fmt"
    	"github.com/astaxie/beego"
    	"github.com/astaxie/beego/orm"
    )
    
    type UserController struct {
          
          
    	beego.Controller
    }
    
    func (self *UserController) Get() {
          
          
    	o := orm.NewOrm()
    	//默认使用default,这里可以不用写
    	//o.Using("default")
    	user := models.User{
          
          Name: "张三", Age: 20, Address: "广东"}
    	id, err := o.Insert(&user)
    	fmt.Println(id)
    	fmt.Println(err)
    	self.TplName = "orm.html"
    }
    
  • 7. View database data

2. Some knowledge supplements about the model

  • 1. About the default table name

    • In addition to the initial capital letters, _ will be increased when encountering capital letters, and the underscore in the original name will be retained
    • Custom table name is the rewrite TableNamemethod
  • 2. Custom field name

    type User struct {
          
          
    	Id int
    	Name string `orm:"column(user_name)"` // 在go代码中用的是Name,在数据库存的是user_name
    	Age int
    	Address string
    }
    
  • 3. Set parameters

    type User struct {
          
          
    	Id int `orm:"pk" "auto"` // 设置主键且自动增长
    	...
    }
    
  • 4. Ignore fields

    type User struct {
          
          
    	...
    	Address string `orm:"-"`
    }
    
  • 5. A relatively complete model

    /**
    	注意beego中创建的表都是非空的,除非自己先指定null
     */
    type User struct {
          
          
    	Id int `json:"id" orm:"pk;auto;description(主键id)"` // 设置主键且自动增长
    	Name string `json:"name" orm:"index;unique;size(50);description(用户名)"` // 唯一的且加了索引的
    	Age int `json:"age" orm:"default(0);description(年龄)"`
    	Salary float64 `json:"price" orm:"digits(12);decimals(2);description(薪资)"`
    	Address string `json:"address" orm:"size(100);null;column(address);description(地址)"` // 可以为空
    	// 创建时间字段
    	CreateAt *time.Time `json:"create_at" orm:"auto_now_add;type(datetime);description(创建时间)"`
    	UpdateAt *time.Time `json:"update_at" orm:"auto_now;type(datetime);description(更新时间)"`
    }
    
    

Three, insert data

  • 1. Use a Insertsimple insert of a piece of data

    func (self *UserController) Get() {
          
          
    	o := orm.NewOrm()
    	//默认使用default,这里可以不用写
    	//o.Using("default")
    	user := models.User{
          
          Name: "张三", Age: 20, Address: "广东"}
    	id, err := o.Insert(&user)
    	fmt.Println(id)
    	fmt.Println(err)
    	self.TplName = "orm.html"
    }
    
  • 2. Use to InsertMultiinsert multiple data

    func (self *UserController) Get() {
          
          
    	// 插入多条数据
    	o := orm.NewOrm()
    	users := []models.User{
          
          {
          
          Name: "李四", Age: 20, Address: "湖南"}, {
          
          Name: "王五", Age: 30, Address: "广西"}}
    	//InsertMulti第一个参数表示一次可以插入100条数据
    	count, err := o.InsertMulti(100, &users)
    	fmt.Println(count)
    	fmt.Println(err)
    
    	self.TplName = "orm.html"
    }
    

Four, delete data

  • 1. Delete according to the field

    func (self *UserController) Get() {
          
          
    	//根据字段删除数据
    	o := orm.NewOrm()
    	user := models.User{
          
          Name: "水痕"}
    	num, err := o.Delete(&user, "Name")
    	fmt.Println(num, err)
    	self.TplName = "orm.html"
    }
    
  • 2. IDDelete according to

    func (self *UserController) Get() {
          
          
    	//根据字段删除数据
    	o := orm.NewOrm()
    	user := models.User{
          
          Id: 1}
      // 根据ID删除可以不用写这个
    	num, err := o.Delete(&user)
    	fmt.Println(num, err)
    	self.TplName = "orm.html"
    }
    

Five, update data

  • 1. Update the data directly

    func (self *UserController) Get() {
          
          
    	//更新数据
    	o := orm.NewOrm()
      // 先查找到数据
    	user := models.User{
          
          Name: "张三"}
    	err := o.Read(&user, "Name")
    	if err == nil {
          
          
        // 修改了什么就更新什么
    		user.Name = "哈哈"
    		user.Address = "南山"
    		num, err := o.Update(&user)
    		print("受影响的行数", num)
    		fmt.Println(err)
    	}
    	self.TplName = "orm.html"
    }
    
  • 2. Specify the updated field

    func (self *UserController) Get() {
          
          
    	//更新数据
    	o := orm.NewOrm()
    	user := models.User{
          
          Name: "张三"}
    	err := o.Read(&user, "Name")
    	if err == nil {
          
          
    		user.Name = "哈哈11"
    		user.Address = "南山"
        // 只更新Name字段,不更新Address字段
    		num, err := o.Update(&user, "Name")
    		print("受影响的行数", num)
    		fmt.Println(err)
    	}
    	self.TplName = "orm.html"
    }
    

Six, query data

  • 1. Use Readto idquery data based on fields

    func (self *UserController) Get() {
          
          
    	// 根据id查询字段
    	o := orm.NewOrm()
    	user := models.User{
          
          Id: 1}
    	o.Read(&user)
    	fmt.Println("查询到的数据", user)
    
    	self.TplName = "orm.html"
    }
    
  • 2. Query according to the specified field

    func (self *UserController) Get() {
          
          
    	//根据别的字段去查询
    	o := orm.NewOrm()
    	user := models.User{
          
          Name: "张三"}
    	o.Read(&user, "Name")
    	fmt.Println("一个字段查询", user)
    
    	user1 := models.User{
          
          Name: "王五", Address: "广西"}
    	o.Read(&user1, "Name", "Address")
    	fmt.Println("多个字段查询", user1)
    	self.TplName = "orm.html"
    }
    
  • 3. Query and create (when you query, if you find that there is no database, create it, and query if there is any)

    func (self *UserController) Get() {
          
          
    	//查询和创建
    	// 查询一个已经有的数据
    	o := orm.NewOrm()
    	user := models.User{
          
          Name: "王五", Age: 30, Address: "广西"}
    	is_new, id, err := o.ReadOrCreate(&user, "Name", "Age", "Address")
    	fmt.Println("第一次结果", is_new, id, err)
    	//查询一个没有的数据
    	user1 := models.User{
          
          Name: "王二", Age: 30, Address: "湖北"}
    	is_new1, id1, err1 := o.ReadOrCreate(&user1, "Name", "Age", "Address")
    	fmt.Println("第二次结果", is_new1, id1, err1)
    	self.TplName = "orm.html"
    }
    // 结果
    // 第一次结果 false 3 <nil>
    // 第二次结果 true 4 <nil>
    

Seven, on the way to use the command

  • 1. main.goOpen the command to build a table in

    func main() {
          
          
    	//全局开启打印sql模式
    	orm.Debug = true
    	//开始数据迁移
    	orm.RunCommand()
    	beego.Run()
    }
    
  • 2. You must register first when creating a model

    // 模型中
    func init()  {
          
          
    	orm.RegisterModel(new(User))
    }
    
  • 3. Run the command

    go run main.go orm // 查看有什么命令
    go run mian.go orm syncdb // 将数据模型同步到数据库
    
  • , ormA little question about

    • Now you can only synchronize the data table once. If you add or remove fields to the model, you cannot synchronize to the database. This is a lack of design and may be improved in the future.
    • Personally suggest that at this stage, we still use manual creation of the table, and then write the model according to the data table

Guess you like

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