models->article.go
models->articleCate.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package models type Article struct { Id int Title string CateId int //外键 State int // ArticleCate ArticleCate `gorm:"foreignKey:CateId"` } //表示配置操作数据库的表名称 func (Article) TableName() string { return "article" } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package models //foreignKey外键 如果是表名称加上Id的话默认也可以不配置 如果不是我们需要通过foreignKey配置外键 //references表示的是主键 默认就是Id 如果是Id的话可以不配置 type ArticleCate struct { Id int //主键 Title string State int Article []Article `gorm: "foreignKey:CateId;references:Id" ` } //表示配置操作数据库的表名称 func (ArticleCate) TableName() string { return "article_cate" } |
controllers->admin->articleController.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package admin import ( "gindemo16/models" "net/http" "github.com/gin-gonic/gin" ) type ArticleController struct { BaseController } func (con ArticleController) Index(c *gin.Context) { //获取所有的文章 // articleList := []models.Article{} // models.DB.Find(&articleList) // c.JSON(200, gin.H{ // "result": articleList, // }) // 查询文章 获取文章对应的分类 // articleList := []models.Article{} // models.DB.Preload("ArticleCate").Find(&articleList) // c.JSON(200, gin.H{ // "result": articleList, // }) //获取所有的分类 articleCateList := []models.ArticleCate{} models.DB.Preload( "Article" ).Find(&articleCateList) c.JSON(200, gin.H{ "result" : articleCateList, }) } func (con ArticleController) Add(c *gin.Context) { c.String(http.StatusOK, "-add--文章-" ) } func (con ArticleController) Edit(c *gin.Context) { c.String(http.StatusOK, "-Edit---文章---" ) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具