一. 官方:https://github.com/go-gorm/datatypes
二. model
type User struct { Name `gorm:"column:name;type:varchar(255);` Attributes datatypes.JSON `gorm:"column:attributes;type:json"` } // 数据内容 user := model.User{ Name: "jsonName", Attributes: datatypes.JSON({"name": "jinzhu", "age": 18, "tags": ["tag1", "tag2"], "orgs": {"orga": "orga1", "orgb": "orgb1", "orgac": "orgc1"}}), }
三. 查询方式
3.1 查询 name=jinzhu
u := query.User u.WithContext(ctx).Where( gen.Cond(datatypes.JSONQuery("attributes").Equals("jinzhu", "name"))..., ).Find()
3.2 多条件查询 orgs.orga=orga1,orgs.orgb=orgb1,orgs.orgc=orgc1
u := query.User cond := u.WithContext(ctx).Clauses() tagList := map[string]string{ "orga": "orga1", "orgb": "orgb1", "orgc": "orgc1", } for k, v := range tagList { cond = cond.OR(gen.Cond(datatypes.JSONQuery("attributes").Equals(v, "orgs", fmt.Sprintf(`"%s"`, k)))...,) } u.WithContext(ctx).Where(cond).Find()
3.3 模糊搜索 tags: ["tag1", "tag2"],通过查询 "tag",获取包含 "tag1", "tag2" 的数据
u := query.User t := "tag" u.WithContext(ctx).Where( gen.Cond(datatypes.JSONQuery("attributes").Likes(fmt.Sprint("%"+t+"%"), "tags"))... )
标签:JSONQuery,查询,JSON,User,orgs,datatypes,gorm From: https://www.cnblogs.com/chaoqi/p/18680450