gorm 一对一 一对多 例子

数据库sql

CREATE TABLE `allin_asset` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `instance_id` varchar(255) DEFAULT '' COMMENT '实例ID',
  `instance_name` varchar(255) DEFAULT '' COMMENT '标签',
  `host_name` varchar(255) DEFAULT '' COMMENT '系统名字',
  `zone` varchar(255) DEFAULT '' COMMENT '可用区',
  `business_id` varchar(255) DEFAULT '' COMMENT '产品线',
  `private_ip` varchar(255) DEFAULT '' COMMENT '内网IP',
  `public_ip` varchar(255) DEFAULT '' COMMENT '外网IP',
  `os_name` varchar(255) DEFAULT '' COMMENT '系统版本',
  `cpu` int(11) unsigned  DEFAULT NULL COMMENT 'CPU',
  `memory` int(11) unsigned  DEFAULT NULL COMMENT '内存',
  `created_on` int(11) unsigned DEFAULT NULL COMMENT '创建时间',
  `modified_on` int(11) unsigned DEFAULT NULL COMMENT '更新时间',
  `expired_on` int(11) unsigned DEFAULT NULL COMMENT '过期时间',
  `status`  varchar(255) DEFAULT '' COMMENT '运行状态',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='资产管理';

CREATE TABLE `allin_business` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255)  COMMENT '产品线名字',
  `created_on` int(11) unsigned DEFAULT NULL COMMENT '创建时间',
  `modified_on` int(11) unsigned DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='产品线管理';

CREATE TABLE `allin_module` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255)  COMMENT '模块名字',
  `created_on` int(11) unsigned DEFAULT NULL COMMENT '创建时间',
  `modified_on` int(11) unsigned DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='模块管理';

CREATE TABLE `allin_asset_module` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `asset_id` int(11) unsigned DEFAULT NULL COMMENT '资产ID',
  `module_id` int(11) unsigned DEFAULT NULL COMMENT '组ID',
  `created_on` int(11) unsigned DEFAULT NULL COMMENT '创建时间',
  `modified_on` int(11) unsigned DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='资产_模块_管理';

表结构

type Business struct {
    Model
    Name string `json:"name"`
}

type Module struct {
    Model
    Name string `json:"name"`
}

type Asset struct {
    Model

    InstanceId   string        `json:"instance_id"`
    InstanceName string        `json:"instance_name"`
    HostName     string        `json:"host_name"`
    Zone         string        `json:"zone"`
    PrivateIp    string        `json:"private_ip"`
    PublicIp     string        `json:"public_ip"`
    OsName       string        `json:"os_name"`
    Cpu          int           `json:"cpu"`
    Memory       int           `json:"memory"`
    ExpiredOn    int           `json:"expired_on"`
    Status       string        `json:"status"`
    BusinessId   int           `json:"business_id" gorm:"index"`
    Business     Business      `json:"business"`     // 产品线   一对一
    Module       []Module `json:"module" gorm:"many2many:asset_module;"`   // 模块  多对多
}

func GetAsset(id int) (asset Asset) {
    db.Where("id = ?", id).First(&asset)
    db.Model(&asset).Related(&asset.Business).Related(&asset.Module, "module")
    return
}

函数

func GetAsset(id int) (asset Asset) {
    db.Where("id = ?", id).First(&asset)
    db.Model(&asset).Related(&asset.Business).Related(&asset.Module, "Module")
    return
}

func GetAssets(pageNum int, pageSize int, maps interface{}) (assets []Asset) {
    db.Preload("Business",).Preload("Module",).Where(maps).Offset(pageNum).Limit(pageSize).Find(&assets)
    return
}

func AddAsset(data map[string]interface{}, modules []int ) bool {
    asset := &Asset{
        InstanceId:   data["instance_id"].(string),
        InstanceName: data["instance_name"].(string),
        HostName:     data["host_name"].(string),
        Zone:         data["zone"].(string),
        BusinessId:   data["business_id"].(int),
        PrivateIp:    data["private_ip"].(string),
        PublicIp:     data["public_ip"].(string),
        OsName:       data["os_name"].(string),
        Cpu:          data["cpu"].(int),
        Memory:       data["memory"].(int),
        ExpiredOn:    data["expired_on"].(int),
        Status:       data["status"].(string),
    }
    module := []Module{}
    db.Where("id in (?)", modules).Find(&module)
    db.Create(&asset).Association("Module").Append(module)  //.Delete   .Replace  .Clear() .Count()

    return true
}

func ExistAssetByID(id int) bool {
    var asset Asset
    db.Select("id").Where("id = ?", id).First(&asset)
    if asset.ID > 0 {
        return true
    }

    return false
}

func DeleteAsset(id int) bool {
    asset := Asset{}
    db.Where("id = ?", id).Find(&asset)
    db.Model(&asset).Association("Module").Clear()
    db.Where("id = ?", id).Delete(asset)

    return true
}

func EditAsset(id int, data interface{},modules []int) bool {
    module := []Module{}
    db.Where("id in (?)", modules).Find(&module)
    asset := Asset{}
    db.Where("id = ?", id).Find(&asset)

    db.Model(&asset).Association("Module").Replace(module)
    db.Model(&asset).Updates(data)

    return true
}