这是我参与11月更文挑战的第23天,活动详情查看:2021最后一次更文挑战
写在前面
第一节,我们确定了
ER图
,数据字典
。
第二节,我们已经配置了MySQL
。
结合前两章,我们就可以建立数据库表了。
- init.go
1 | go复制代码package model |
- user
用户表
1 | go复制代码type User struct { |
- product 商品表
1 | go复制代码type Product struct { |
- ProductImg 商品图片表
1 | go复制代码type ProductImg struct { |
- ProductParamImg 商品参数表
1 | go复制代码type ProductParamImg struct { |
- ProductInfoImg 商品详情表
1 | go复制代码type ProductInfoImg struct { |
- 购物车表
1 | go复制代码type Cart struct { |
- Order 订单表
1 | go复制代码type Order struct { |
- 地址表
1 | go复制代码type Address struct { |
- 收藏表
1 | go复制代码type Favorite struct { |
- 分类表
1 | go复制代码type Category struct { |
- 管理员表
1 | go复制代码type Admin struct { |
- 轮播图表
1 | go复制代码type Carousel struct { |
- 做迁移并加上外键约束
1 | go复制代码func migration() { |
AutoMigrate
函数是把代码映射到数据库中AddForeignKey
函数是添加外键
举例子
1 | go复制代码DB.Model(&Cart{}).AddForeignKey("product_id","Product(id)","CASCADE","CASCADE") |
这个函数就是在Cart
表中把product_id
字段关联到product
的id
中,后面两个就是update
和delete
的时候进行级联更新
或是级联删除
。
本文转载自: 掘金