V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
zxCoder

伸手求一个 gorm 的查询方法

  •  
  •   zxCoder · Oct 29, 2020 · 977 views
    This topic created in 2012 days ago, the information mentioned may be changed or developed.

    看了一上午文档还没写出来

    post tag post_tag_relation 三个表,post 和 tag 是多对多关系

    现在要从关系表中查找某个 tagId 对应的所有 postId,再查这些 postId 对应的 post 信息,就包括把每个 post 对应的所有 tag 也查出来,有什么方便的方法吗

    因为查询条件不确定,所以目前是这样写的

    tagId,ok:=para["tagId"]
    	if ok{
    		tagId=int(tagId.(float64))
    		var postIds []int64
    		var rels []models.PostTagRelation
    		err := db.Table("post_tag_relation").Where("tag_id=?", tagId).Where("del=?",0).Select("postId").Find(&rels).Error
    		if err != nil {
    			log.Println("query error: ", err)
    			c.JSON(200, failResp)
    			return
    		}
    		for _, rel := range rels {
    			postIds = append(postIds, rel.PostId)
    		}
    		db2=db2.Where("id in (?)",postIds)
    	}
    
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2452 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 04:53 · PVG 12:53 · LAX 21:53 · JFK 00:53
    ♥ Do have faith in what you're doing.