gorm:结合Model进行数据映射

0、有这样一张表

CREATE TABLE `news_category` (
  `category_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `category_name` varchar(255) DEFAULT NULL,
  `category_remark` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='新闻分类表';

1、和模型映射

package model

type NewsCategoryModel struct {
	CategoryId int
	CategoryName string
	CategoryRemark string
}

3、测试几个功能
文档地址:http://gorm.io/docs/query.html

	db, err := gorm.Open("mysql", "root:root@/test?charset=utf8mb4&parseTime=True&loc=Local")
	defer db.Close()
	if err != nil {
		log.Fatal(err)
	}
	// 打开日志日志,查看执行的sql
	db.LogMode(true)

	model := &model.NewsCategoryModel{}
	db.Table("news_category").First(&model) //指定表名称,取第一条
	fmt.Println(model) //打印:&{1 财经 财经类节目说明}

成功取出表第一行数据

4、字段映射

CREATE TABLE `news_category` (
  `category_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `category_name` varchar(255) DEFAULT NULL,
  `category_remark` varchar(255) DEFAULT NULL,
  `type` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='新闻分类表';

表字段中有type

type NewsCategoryModel struct {
	CategoryId int
	CategoryName string
	CategoryRemark string
	CategoryType int //如何映射
}

模型中定义的是CategoryType,如何映射?

type NewsCategoryModel struct {
	CategoryId     int
	CategoryName   string
	CategoryRemark string
	CategoryType   int `gorm:"Column:type"`
}

详细用法参考文档:http://gorm.io/docs/models.html

5、根据主键ID来取

	//
	db.Table("news_category").First(&model, 2)

这样可以吗?不行。
它执行的sql是这样的:

 SELECT * FROM `news_category`  WHERE (`news_category`.`` = 2) LIMIT 1  

没有指定主键字段是哪个


type NewsCategoryModel struct {
	CategoryId     int	`gorm:"PRIMARY_KEY"`
	CategoryName   string
	CategoryRemark string
	CategoryType   int `gorm:"Column:type"`
}

这样就好了。

6、取出多条

	//定义切片
	var categorys []model.NewsCategoryModel

	//where条件查询
	db.Table("news_category").Find(&categorys)
	fmt.Println(categorys)	//打印:[{1 财经 财经类节目说明 1} {2 技术 技术类节目说明 2} {3 体育 体育类节目说明 3}]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值