go-xorm別名使用

簡介

須要別名的場景有兩種:數據庫

  • 表名太長,須要給Table起別名
  • Inner join

一個不嚴謹的演示案例

承接上文,使用我這篇記錄裏的不嚴謹案例ui

一種狀況

添加一個特別的輔助結構體

type MailBoxAddress{
    Mailbox `xorm:"extends"`
    Addr string
}

獲取實例的方法

func GetMailBoxAddress(engine *xorm.Engine, addr string, num int64) (addr *MailBoxAddress,had bool,err error){
    addr = &MailBoxAddress{}
    has,err = engine.Table("mailboxes").Alias("box").Select("box.*, buildings.addr").
        Join("INNER","buildings","box.building_id = buildings.id").
        Where("building.addr = ?",addr).And("box.num = ?",num).Get(addr)
    if err !=nil{
        err = fmt.Errorf("GetMailBoxAddress:%v",err)
    }
    return
}

這樣就能夠在box數據庫沒必要增長addr字段的狀況下獲取到每條記錄對應的地址了.net

另外一種狀況

第一種狀況只是兩個表聯查,當須要三個表聯查時code

輔助結構體

與上一篇記錄中的 BuildingMailboxLink 不一樣,不適用定義表的結構體,而使用上文中定義的輔助結構體,以下orm

type MailAddrBuildingLink struct{
    MailBoxAddress `xorm:"extends"`
    Building `xorm:"extends"`
    Link `xorm:"extends"`
}

這時,因爲mailboxaddr查詢與building內聯,出現了須要給inner join的表添加別名的狀況blog

獲取實例的方法

func GetMailBoxAddrBuildingLink(engine *xorm.Engine, addr string, num int64,buildingAddr string) (addr *MailAddrBuildingLink ,had bool,err error){
    addr = &MailBoxAddress{}
    has,err = engine.Table("mailboxes").Alias("box").Select("box.*, mailbuilding.addr,buildings.*,links.*").
        Join("INNER",[]string{"buildings","mailbuilding"},"box.building_id = mailbuilding.id").
        Join("INNER","links","box.id = links.mailbox_id").
        Join("INNER","buildings","links.building_id = buildings.id").
        Where("mailbuilding.addr = ?",addr).
        And("box.num = ?",num).
        And("buildings.addr = ?",buildingAddr ).Get(addr)
    if err !=nil{
        err = fmt.Errorf("GetMailBoxAddrBuildingLink:%v",err)
    }
    return
}

這裏經過一個 []string{} slice給「buidings」表起了一個別名「mailbuilding」文檔

小結

方法不難,一點就通,但在官方文檔上很差找。get

相關文章
相關標籤/搜索