主外键
定义user表
type User struct {
gorm.Model
Name string
Sex int8 `gorm:"default:0"`
Account string `gorm:"not null;"`
Password string `gorm:"not null"`
LastLoginAt time.Time `gorm:"default:null"`
Phone string `gorm:"not null;"`
Role Role `gorm:"foreignKey:role_id"`
// 必须定义额外的外键字段
RoleId uint
}
定义role表
type Role struct {
gorm.Model
RoleName string `gorm:"not null;"`
}
外键联查时必须使用预加载
var user User
DB.Preload("Role").Where(&User{RoleId: role1.ID}).First(&user)
IN
userIds := []uint{1, 2, 3, 4, 5}
DB.Preload("Role").Where("id IN (?)", userIds).First(&user)
返回特定字段
type Equipment struct {
gorm.Model
EquipmentName string `gorm:"not null;"` // 设备名称
EquipmentType EquipmentType `gorm:"foreignKey:equipment_type_id"`
EquipmentTypeId uint
ManufacturingCell ManufacturingCell `gorm:"foreignKey:manufacturing_cell_id"`
ManufacturingCellId uint
EquipmentComType uint8 `gorm:"default:1"`
Port uint
IPOrCom string
UserName string
Password string
HomePath string
TrialCutPath string
BunkerLevel uint // 料仓料位个数
BunkerWidth uint // 料仓料位宽度
BunkerHeight uint // 料仓料位高度
Status uint8 `gorm:"default:1"`
//ToolId uint
}
返回特定字段
type EquipmentAPI struct {
gorm.Model
EquipmentName string
EquipmentTypeId uint
ManufacturingCellId uint
EquipmentComType uint8
IPOrCom string
Port uint
Status uint8
}
var equipments []EquipmentAPI
DB.Table("equipment").Where("equipment_type_id = ?", equipmentTypeId).Where("manufacturing_cell_id = ?", mcId).Scan(&equipments)
外键为空时异常
在外键后添加tag
`gorm:"default:'galeone'"`
更新外键为nil
tx.Table("ecdc_bind_equipments").Where("equipment_id = ?", equipmentId).Where("energy_consumption_data_collector_id = ?", ecdcId).Updates(map[string]interface{}{"equipment_id": nil})
条件为False查询
使用
model.DB.Not(&model.Equipment{IsBindECDC: true}).Find(&equipments)
而不能使用
model.DB.Where(&model.Equipment{IsBindECDC: false}).Find(&equipments)
数据去重(distinct)
// ExamSessionSelect 场次下拉菜单
type ExamSessionSelect struct {
ExamSession string
ExamId uint
}
model.DB.Table("boms").Select("distinct exam_session,exam_id").Where(&model.Bom{ExamineesId: examineesId}).Scan(&boms)