Gorm踩坑指南

主外键

定义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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值