Golang beego ORM + CRUP 操作详解
构建beego Web 项目
首先构建一个beego 的web 项目,这个我们完全可以参考beego 官网中的开发文档,上面介绍的非常的详细,在这我就不给大家介绍,主要是介绍ORM 的CRUP 的操作;这是beego 的官网 https://beego.me/docs/intro/
CRUP 操作
使用的ORM 的操作,大致步骤是首先创建 数据库的实例,Model实体,控制器 ,还有View 视图;我的实例中使用的是MySQL 数据库;所用应用的数据库驱动也是MySQL 的。
代码块
第一: 数据库实例
package models import ( "github.com/astaxie/beego" "github.com/astaxie/beego/orm" _ "github.com/go-sql-driver/mysql" ) func init() { mysqluser := beego.AppConfig.String("mysqluser") mysqlpass := beego.AppConfig.String("mysqlpass") mysqlurls := beego.AppConfig.String("mysqlurls") mysqldb := beego.AppConfig.String("mysqldb") orm.RegisterModel(new(DbBrand), new(DbProduct)) orm.RegisterDriver("mysql", orm.DRMySQL) orm.RegisterDataBase("default", "mysql", mysqluser+":"+mysqlpass+"@tcp("+mysqlurls+")/"+mysqldb+"?charset=utf8&loc=Asia%2FShanghai") orm.RunSyncdb("default", false, true) if beego.AppConfig.String("runmode") == "dev" { orm.Debug = true } }
第二:实体,下面我是创建了两个实体,这个两个实体是有关系,但是在实例中并没有使用它们的关系进行数据库的操作,这个后续为大家补上的。 有关创建model 实体的关系,在beego 开发文档说明的很清楚了我就不这里解析了。
Brand 实体
package models import ( "time" "github.com/astaxie/beego/orm" ) type DbBrand struct { BrandID int64 `orm:"auto;pk;column(BrandID);" json:"BrandID"` BrandName string `orm:"size(100);column(BrandName);"json:"BrandName"` SortID int64 `orm:"column(SortID)"` Memo string `orm:"size(500);column(Memo);"` CreateTime time.Time `orm:"auto_now;type(datetime);column(CreateTime)"` Product []*DbProduct `orm:"reverse(many)"` } func (b *DbBrand) TableName() string { return "_Brand" } func (b *DbBrand) Query() orm.QuerySeter { return orm.NewOrm().QueryTable(b) } func (b *DbBrand) Insert() (int64, error) { return orm.NewOrm().Insert(b) } func (b *DbBrand) Delete() (int64, error) { num, err := orm.NewOrm().Delete(b) if err != nil { return 0, err } return num, nil } func (b *DbBrand) Update(fields ...string) error { _, err := orm.NewOrm().Update(b, fields...) if err != nil { return err } return nil } func (b *DbBrand) Read(fields ...string) error { err := orm.NewOrm().Read(b, fields...) if err != nil { return err } return nil }
Product实体
package models import ( "time" "github.com/astaxie/beego/orm" ) type DbProduct struct { ProductID int32 `orm:"auto;pk;column(ProductID);" json:"ProductID"` Name string `orm:"size(100);column(Name)"` Store int32 `orm:"column(Store);"` CostPrice float32 `orm:"digits(12);decimals(2);column(CostPrice)"` SalePrice float32 `orm:"digits(12);decimals(2);column(SalePrice)"` MarketPrice float32 `orm:"digits(12);decimals(2);column(MarketPrice)"` Memo string `orm:"size(500);null;column(Memo)"` Code string `orm:"size(100);column(Code)"` OpEmployeeID int32 `orm:"column(OpEmployeeID);"` UseIntegralRule int32 `orm:"column(UseIntegralRule);"` DeductionIntegralRule int32 `orm:"column(DeductionIntegralRule);"` Unit string `orm:"size(100);column(Unit)"` Weight string `orm:"size(100);column(Weight)"` ReturnIntegralRule int32 `rm:"column(ReturnIntegralRule);"` ReturnIntegralRuleValue int32 `orm:"column(ReturnIntegralRuleValue);"` ReturnIntegralValue int32 `orm:"column(ReturnIntegralValue);"` IsAudit bool `orm:"column(IsAudit)"` IsHaveInvoice bool `orm:"column(IsHaveInvoice)"` CreateTime time.Time `orm:"auto_now;type(datetime);column(CreateTime)"` UpdateTime time.Time `orm:"auto_now;type(datetime);column(UpdateTime)"` Brand *DbBrand `orm:"rel(fk);null;on_delete(do_nothing);"` // Type *DbProductType `orm:"rel(fk);null;on_delete(do_nothing);"` // Channel *DbChannel `orm:"rel(fk);null;on_delete(do_nothing);"` // ProductColor []*DbProductColor `orm:"reverse(many)"` // ProductSize []*DbProductSize `orm:"reverse(many)"` // ProductImage []*DbProductImage `orm:"reverse(many)"` // ProductService []*DbProductService `orm:"reverse(many)"` // OrderItem []*DbOrderItem `orm:"null;reverse(many)"` } func (b *DbProduct) TableName() string { return "_Product" } func (b *DbProduct) Query() orm.QuerySeter { return orm.NewOrm().QueryTable(b) } func (b *DbProduct) Insert() (int64, error) { return orm.NewOrm().Insert(b) } func (b *DbProduct) Delete() error { _, err := orm.NewOrm().Delete(b) if err != nil { return err } return nil } func (b *DbProduct) Update(fields ...string) error { _, err := orm.NewOrm().Update(b, fields...) if err != nil { return err } return nil } func (b *DbProduct) Read(fields ...string) error { err := orm.NewOrm().Read(b, fields...) if err != nil { return err } return nil }
Controller 控制器的操作
package controllers import ( "strconv" "strings" "time" models "wechatSystem/models" "github.com/astaxie/beego" ) type BrandController struct { baseController } //品牌列表页 func (this *BrandController) Get() { this.Data["Title"] = "品牌管理" this.TplName = "Brand/Index.html" var dbBrand models.DbBrand var list []*models.DbBrand dbBrand.Query().OrderBy("-sortID").All(&list) this.Data["list"] = list } //查询品牌 func (this *BrandController) SeachIndex() { brandName := this.GetString("Keys") this.TplName = "Brand/Index.html" var dbBrand models.DbBrand var list []*models.DbBrand //模糊查询 dbBrand.Query().Filter("BrandName__icontains", brandName).All(&list) this.Data["list"] = list } //品牌添加 func (this *BrandController) Add() { this.TplName = "Brand/Details.html" } //详情 func (this *BrandController) Details() { brandId, _ := strconv.ParseInt(this.Ctx.Input.Param(":id"), 10, 64) //查询品牌分类集合 var dbBrandList []*models.DbBrand var dbBrand models.DbBrand dbBrand.Query().All(&dbBrandList) if brandId <= 0 { this.Showmsg("编辑数据错误,返回重试...") } //根据ID 进行查询 dbBrand.BrandID = brandId err := dbBrand.Read() if err != nil { this.Showmsg("该数据不存在...") } this.Data["BrandId"] = brandId this.Data["BrandName"] = dbBrand.BrandName this.Data["StorId"] = dbBrand.SortID this.Data["Memo"] = dbBrand.Memo this.TplName = "Brand/Details.html" } //保存品牌 func (this *BrandController) Save() { var err error var brandModel models.DbBrand brandID, _ := this.GetInt64("brandId") brandName := strings.TrimSpace(this.GetString("BrandName")) sortID, _ := this.GetInt64("SortId") memo := strings.TrimSpace(this.GetString("Memo")) SaveRule := this.GetString("SaveRule") brandModel.BrandName = brandName brandModel.SortID = sortID brandModel.Memo = memo brandModel.CreateTime = time.Now() if len(brandName) == 0 { this.Showmsg("品牌名称不能为空!") } if brandID > 0 { //编辑更新 brandModel.BrandID = brandID err = brandModel.Update("BrandName", "SortID", "Memo", "CreateTime") } else { //添加信息 _, err = brandModel.Insert() } // if err != nil { // this.Showmsg("保存出错,错误信息:" + err.Error()) // } else { // this.Showmsg("保存成功!") // } if err != nil { this.Showmsg("保存出错,错误信息:" + err.Error()) } if SaveRule == "SaveReturnList" { //this.TplName = "Brand/Index.html" this.Ctx.Redirect(302, "/Brand") return } //this.Ctx.Redirect(302, "/Brand/Details/0") this.TplName = "Brand/Details.html" } //重新排序 func (this *BrandController) SaveSortId() { var err error //var modelList []Model var brands []string var sortIDs []string this.Ctx.Input.Bind(&brands, "brandId") this.Ctx.Input.Bind(&sortIDs, "sortId") // brandId, _ := strconv.ParseInt(this.GetString("brandId"), 10, 64) // sortId, _ := strconv.ParseInt(this.GetString("SortID"), 10, 64) this.TplName = "Brand/Index.html" for i := 0; i < len(brands); i++ { for j := 0; j < len(sortIDs); j++ { var dbBrand models.DbBrand sID, _ := strconv.ParseInt(sortIDs[j], 10, 64) dbBrand.SortID = sID dbBrand.CreateTime = time.Now() bID, _ := strconv.ParseInt(brands[i], 10, 64) if dbBrand.Query().Filter("BrandId", bID).Exist() { dbBrand.BrandID = bID err = dbBrand.Update("SortID", "CreateTime") } } } if err == nil { this.Data["json"] = map[string]interface{}{"Isuccess": "true"} } else { this.Data["json"] = map[string]interface{}{"Isuccess": "false"} } this.ServeJSON() } //删除 func (this *BrandController) Delete() { brandId, _ := strconv.ParseInt(this.GetString("brandId"), 10, 64) this.TplName = "Brand/Index.html" var dbBrand models.DbBrand if dbBrand.Query().Filter("BrandId", brandId).Exist() { dbBrand.BrandID = brandId if num, err := dbBrand.Delete(); err == nil { beego.Info("Brand delete", num) this.Data["json"] = map[string]interface{}{"Isuccess": "true"} } else { beego.Error("Brand couldn't be delete. Reason", err) this.Data["json"] = map[string]interface{}{"Isuccess": "false"} } this.ServeJSON() } }
View 视图 视图中使用了模板页
{{template "layout/basemain.html" .}} {{define "layout/body.html"}} <div class="location"> <a class="home"><i></i></a><span>当前页面:金色平台</span> <i class="arrow"></i> <span>品牌维护</span> </div> <form id="searchForm" action="/Brand/SeachIndex" method="post" > <!--工具栏--> <div class="toolbar-wrap"> <div id="floatHead" class="toolbar"> <div class="l-list"> <ul class="icon-list"> <li><a class="add" href="/Brand/Add"><i></i><span>添加</span></a></li> <li><a id="selectAll" href="javascript:;" class="all"><i></i><span>全选</span></a></li> <li><a id="saveBrandId" href="javascript:;" class="save"><i></i><span>保存</span></a></li> <li><a id="delete" href="javascript:;" class="del"><i></i><span>删除</span></a></li> </ul> </div> <div class="r-list"> <input type="text" name="Keys" class="keyword" /> <a id="lbtnSearch" class="btn-search" href="javascript:;" onclick="$('#searchForm').submit();">查询</a> </div> </div> </div> <!--/工具栏--> </form> <table class="ltable" style="margin-top:10px;text-align: center;"> <thead> <tr> <td>选择</td> <td>商品品牌</td> <td>排序</td> <td>创建时间</td> <td>操作</td> </tr> </thead> <tbody> {{range .list}} <tr> <td><input id="BrandId" name="BrandId" type="checkbox" class="checkall" value="{{.BrandID}}"/> </td> <!--<td>{{.BrandID}}</td>--> <td>{{.BrandName}}</td> <td><input id="BrandId{{.BrandID}}" name="SortID" type="text" value="{{.SortID}}" class="sort" /></td> <td>{{dateformat .CreateTime "2006-01-02 15:04"}}</td> <td><a href="/Brand/Details/{{.BrandID}}"> 编辑 </a></td> </tr> {{end}} </tbody> </table> {{end}} <script type="text/javascript"> $(function(){ //全选功能 start $("#selectAll").click(function(){ $(".checkall").each(function(){ this.checked = !this.checked }) }) //end //排序功能 start $("#saveBrandId").click(function(){ if($(":checkbox:checked[name='BrandId']").length == 0){ wxframe.warn("请选择需要操作的项!"); return; } var brandIds = []; var sortIdS = []; $(":checkbox:checked[name='BrandId']").each(function(){ var SortID = $("#BrandId"+ this.value).val(); <!--brandIds.push({BrandId:this.value,SortID:SortID})--> brandIds.push(this.value) sortIdS.push(SortID) }) $.ajax({ url: '/Brand/SaveSortId', data: { brandId:brandIds,sortId : sortIdS }, dataType: 'json', type: 'post', success: function (json) { if (json.Isuccess) { location.href = '/Brand'; } } }); }) //删除功能 start $("#delete").click(function(){ if($(":checkbox:checked[name='BrandId']").length == 0){ wxframe.warn("请选择需要操作的项!"); return; } wxframe.confirm("您确定要删除服务名称吗?",function(){ var brandIds = []; $(":checkbox:checked[name='BrandId']").each(function(){ brandIds.push(this.value) }) $.ajax({ url : '/Brand/Delete', data : {brandId:brandIds[0]}, dataType : 'json', type : 'post', success : function(json){ if(json.Isuccess){ wxframe.success("删除成功!") location.href = "/Brand" } } }) }) }) //end }) </script>
详情页:
{{template "layout/basemain.html" .}} {{define "layout/body.html"}} <div class="location"> <a class="home"><i></i></a><span>当前页面:金色平台</span> <i class="arrow"></i> <span>品牌维护</span> </div> <div class="content-tab-wrap"> <div id="floatHead" class="content-tab"> <div class="content-tab-ul-wrap"> <ul> <li><a href="javascript:" class="selected"> 基本信息 </a></li> </ul> </div> </div> </div> <form id="form1" method="post" action="/Brand/Save" > <div class="tab-content"> <dl> <dt>品牌名称:</dt> <dd><input type="text" name="BrandName" value="{{.BrandName}}" class="input normal" /> </dd> </dl> <dl> <dt>排序:</dt> <dd><input type="text" name="SortId" value="{{.StorId}}" class="input normal" /> </dd> </dl> <dl> <dt>备注:</dt> <dd> <input type="textarea" name="Memo" class="input" style="width:24%;height:150px;" datatype="*0-300" tip="300个字符以内。" value="300个字符以内。"/> </dd> </dl> </div> <!--工具栏--> <div class="page-footer"> <div class="btn-list btn"> <input type="hidden" name="brandId" value="{{.BrandId}}" /> <input type="hidden" name="SaveRule" id="SaveRule" /> <input type="submit" class="btn" value="保存" onclick="$('#SaveRule').val('SaveReturnList')" /> <input type="submit" class="btn" value="保存并继续" onclick="$('#SaveRule').val('SaveAndNext')" /> <input type="button" class="btn yellow" value="返回列表" onclick="location.href = '/Brand';" /> </div> <div class="clear"></div> </div> <!--/工具栏--> </form> {{end}}
路由注册
有关路由的注册规则,可以参考beego 中的开发文档路由设置中有详细的介绍
package routers import ( "wechatSystem/controllers" "github.com/astaxie/beego" ) func init() { beego.Router("/", &controllers.MainController{}) //品牌维护 beego.Router("/Brand", &controllers.BrandController{}) //添加品牌 beego.Router("/Brand/Add", &controllers.BrandController{}, "*:Add") //删除品牌 beego.Router("/Brand/Delete", &controllers.BrandController{}, "*:Delete") //编辑品牌 beego.Router("/Brand/Details/:id([0-9]+)", &controllers.BrandController{}, "*:Details") //保存品牌 beego.Router("/Brand/Save", &controllers.BrandController{}, "post:Save") //保存排序 beego.Router("/Brand/SaveSortId", &controllers.BrandController{}, "*:SaveSortId") //搜索品牌 beego.Router("/Brand/SeachIndex", &controllers.BrandController{}, "*:SeachIndex") }
本文只提供了一下 实例的代码,有什么问题请留言,谢谢;相互学习,共同进步!!!