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
}
View Code

 

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
}
View Code

 

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 Code

 

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>
View Code

 

詳情頁:
{{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}}
View Code

 

路由註冊
 有關路由的註冊規則,能夠參考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")

}
View Code

 

 本文只提供了一下 實例的代碼,有什麼問題請留言,謝謝;相互學習,共同進步!!!
相關文章
相關標籤/搜索