我最近也是開始學Go語言,之前我的項目使用PHP編寫的旧噪,最近想用Go語言重寫一遍尖坤。PHP框架自帶的ORM很好用囱持,但是GO語言的Gorm框架剛剛接觸把我搞得有點蒙夯接,也查了好多網(wǎng)上寫的文章,都沒有太好的解決我的問題纷妆。經(jīng)過我不懈的努力終于搞定了,所以就記錄一下晴弃。
我具體聲明的結(jié)構(gòu)體如下所示:
//設備結(jié)構(gòu)體
type SmartDevice struct {
ID uint `gorm:"column:id" gorm:"primary_key" json:"id"`
DeviceHexCode string `gorm:"column:device_hex_code" json:"device_hex_code"`
DeviceCode string `gorm:"column:device_code" json:"device_code"`
DeviceName string `gorm:"column:device_name" json:"device_name"`
Pid int `gorm:"column:pid" json:"pid"`
Position string `gorm:"column:position" json:"position"`
Ip string `gorm:"column:ip" json:"ip"`
DeviceStatus int `gorm:"column:device_status" json:"device_status"`
AreaId int `gorm:"column:area_id" json:"area_id"`
DeviceType int `gorm:"column:device_type" json:"device_type"`
CreatedTime int `gorm:"created_time" json:"created_time"`
CreatedDate string `gorm:"created_date" json:"created_date"`
UpdatedTime int `gorm:"updated_time" json:"updated_time"`
UpdatedDate string `gorm:"updated_date" json:"updated_date"`
BillDate string `gorm:"bill_date" json:"bill_date"`
//柜子和單元格是一對多的關系
DeviceCell []DeviceCell `gorm:"ForeignKey:DeviceHexCode;AssociationForeignKey:DeviceHexCode" json:"device_cell"`
}
//單元格結(jié)構(gòu)體
type DeviceCell struct {
ID uint `gorm:"primary_key" gorm:"column:id" json:"id"`
DeviceHexCode string `gorm:"column:device_hex_code" json:"device_hex_code"`
CellHexCode string `gorm:"column:cell_hex_code" json:"cell_hex_code"`
Column int `gorm:"column" json:"column"`
Row int `gorm:"row" json:"row"`
Status int `gorm:"status" json:"status"`
CreatedTime int `gorm:"created_time" json:"created_time"`
CreatedDate string `gorm:"created_date" json:"created_date"`
UpdatedTime int `gorm:"updated_time" json:"updated_time"`
UpdatedDate string `gorm:"updated_date" json:"updated_date"`
BillDate string `gorm:"bill_date" json:"bill_date"`
}
他們之間的關系:一個設備對應多個單元格掩幢,所以他是一對多的關系,在聲明關系時上鞠,要定義關聯(lián)關系的外鍵:ForeignKey:DeviceHexCode;AssociationForeignKey:DeviceHexCode
實現(xiàn)這個一對多的查詢有兩種辦法
Preload
preload它的參數(shù)是一個字段名字际邻,具體的實現(xiàn)如下所示:
var smartDevice []model.SmartDevice
db := device.Db.Connect()
defer db.Close()
db.Find(&smartDevice)
data := db.Model(&smartDevice).
Preload("DeviceCell").
Find(&smartDevice)
這樣寫的好處是,我們查詢所有關聯(lián)的時候芍阎,他會給每個條信息帶上關聯(lián)的信息世曾,這和PHP Laravel框架的self::with('relationCell')->where($condition)->get()->toArray();
這種用法是一樣的,返回的數(shù)據(jù)類型效果為:
[
{
"ID" : 1,
"detail" : [
{
"ID" : 33232
}
]
},
{
"ID" : 2,
"detail" : [
{
"ID" : 88877
}
]
}
]
Related
對于Related谴咸,他必須傳一個字段轮听,作為關聯(lián)信息的映射,他的具體用法如下所示:
var smartDevice model.SmartDevice
db := device.Db.Connect()
defer db.Close()
db.Find(&smartDevice)
data := db.Model(&smartDevice).
Related(&smartDevice.DeviceCell, "DeviceCell").
Find(&smartDevice)
這種寫法岭佳,在查詢語句的時候血巍,關聯(lián)數(shù)據(jù)返回都是有一條,對于Find查詢珊随,他會返回最后一條數(shù)據(jù):
{
"ID" : 2,
"detail" : [
{
"ID" : 88877
}
]
}
總結(jié):如果需要查出所有關聯(lián)的數(shù)據(jù)就用Preload述寡,查一條關聯(lián)數(shù)據(jù)用Related