beego的ORM模型增删改查

首先建立一个模型 在 项目/models/testModels.go
package models

import (
	"github.com/astaxie/beego/orm"     //引入beego的orm
	_ "github.com/go-sql-driver/mysql" //引入beego的mysql驱动
)

//表go_archives的结构
type Archives struct {
	Id     int
	Typeid int
	Title  string `orm:"size(255)"`
	Body   string `orm:"size(1000)"`
}

//表go_arctype的结构
type Arctype struct {
	Id       int
	Topid    int
	Typename string `orm:"size(100)`
	Sort     int
}

func init() {
	orm.RegisterDriver("mysql", orm.DR_MySQL)                                //注册数据库驱动
	orm.RegisterDataBase("default", "mysql", "root:123456@/go?charset=utf8") //注册一个别名为default的数据库
	orm.SetMaxIdleConns("default", 30)                                       //设置数据库最大空闲连接
	orm.SetMaxOpenConns("default", 30)                                       //设置数据库最大连接数
	orm.RegisterModelWithPrefix("go_", new(Archives))                        //注册模型并使用表前缀
	orm.RegisterModelWithPrefix("go_", new(Arctype))                         //注册模型并使用表前缀
}

func (this *Archives) Show() ([]Archives, error) {
	o := orm.NewOrm()
	var data []Archives
	_, err := o.QueryTable("go_archives").Filter("id__gt", 3).All(&data)
	return data, err

}

//表go_archives的增加
func (this *Archives) Add(title, body string, typeid int) (int64, error) {
	o := orm.NewOrm()
	arc := Archives{Title: title, Body: body, Typeid: typeid}
	id, err := o.Insert(&arc)
	return id, err
}

func (this *Archives) Edit(title, body string, typeid, id int) error {
	o := orm.NewOrm()
	arc := Archives{Title: title, Body: body, Typeid: typeid, Id: id}
	_, err := o.Update(&arc)
	return err
}

func (this *Archives) Delete(id int) error {
	o := orm.NewOrm()
	arc := Archives{Id: id}
	_, err := o.Delete(&arc)
	return err
}


现在到控制器中看看我们怎么调用模型的方法的实现(增、删、改、查)项目/controllers/test.go

package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strconv"
	"test/models"
)

type TestController struct {
	beego.Controller
}

var arc models.Archives

func (this *TestController) Show() {
	data, err := arc.Show()
	fmt.Println(data, err)
}

func (this *TestController) Add() {
	title := "测试标题"
	body := "测试内容"
	typeid := 1
	id, err := arc.Add(title, body, typeid)
	fmt.Println(id, err)
}

func (this *TestController) Edit() {
	title := "测试标题"
	body := "测试内容"
	typeid := 1
	id := 1
	err := arc.Edit(title, body, typeid, id)
	fmt.Println(err)
}

func (this *TestController) Delete() {
	id := 1
	err := arc.Delete(id)
	fmt.Println(err)
}



go的结构很灵活,beego的框架很简单,只要是略懂MVC就行了,关键部分在GO的基础



转载于:https://my.oschina.net/tongjh/blog/203304

你可能感兴趣的:(beego的ORM模型增删改查)