diff --git a/api/graphql.go b/api/graphql.go index 6de1c3a..90e8e58 100644 --- a/api/graphql.go +++ b/api/graphql.go @@ -1,9 +1,11 @@ package api import ( + "encoding/json" "fmt" "log" "reflect" + "sort" "strconv" "strings" @@ -351,6 +353,7 @@ func NewSchema(config Config) (graphql.Schema, error) { }, }), Args: graphql.FieldConfigArgument{ + "follower": &graphql.ArgumentConfig{Type: graphql.Int, Description: "获取指定ID用户的关注列表发布的图像"}, "interest": &graphql.ArgumentConfig{Type: graphql.Int, Description: "获取指定ID用户的兴趣推荐图像"}, "similar": &graphql.ArgumentConfig{Type: graphql.Int, Description: "获取与指定ID图像相似的图像"}, "id": &graphql.ArgumentConfig{Type: graphql.Int, Description: "获取指定ID的图像"}, @@ -384,6 +387,7 @@ func NewSchema(config Config) (graphql.Schema, error) { Text string Interest int Similar int + Follower int } mapstructure.Decode(p.Args, &args) @@ -471,6 +475,49 @@ func NewSchema(config Config) (graphql.Schema, error) { fmt.Println("Interest:", args.Interest) } + // 筛选: 关注列表 + if args.Follower != 0 { + // 返回JSON数组(2.5秒) + var item string + if err := db.Raw(` + SELECT JSON_ARRAYAGG(web_images.id) AS json_result + FROM web_fans + INNER JOIN web_images ON web_images.user_id = web_fans.blogger_id + WHERE web_fans.follower_id = ? + `, args.Follower).Scan(&item).Error; err != nil { + fmt.Println("获取关注列表失败", err) + return nil, err + } + + var ids []int + json.Unmarshal([]byte(item), &ids) + + sort.Slice(ids, func(i, j int) bool { + return ids[i] > ids[j] // 按照降序排列 + }) + + id_list = append(id_list, ids) + + //fmt.Println(item) + + // 返回所有结果(7秒) + //var item []int + //if err := db.Table("web_fans").Select("web_images.id").Limit(10).Joins("inner join web_images on web_images.user_id = web_fans.blogger_id").Where("web_fans.follower_id = ?", 46).Pluck("id", &item).Error; err != nil { + // fmt.Println("获取关注列表失败", err) + // return nil, err + //} + // id_list = append(id_list, item) + + // 直接出结果(最快) + //var q = db.Table("web_fans").Select("web_images.*").Limit(10) + //q = q.Joins("inner join web_images on web_images.user_id = web_fans.blogger_id") + //q = q.Where("web_fans.follower_id = ?", 46).Preload("User").Preload("Article").Find(&images) + //return map[string]interface{}{ + // "list": images, + // "total": len(images), + //}, nil + } + // 排序 // 截取:取交集 diff --git a/api/struct.go b/api/struct.go index 9bdb8a5..db4b5e5 100644 --- a/api/struct.go +++ b/api/struct.go @@ -87,6 +87,11 @@ type TextList []struct { } func (a *TextList) Scan(value interface{}) error { + // 如果数据库中的值为NULL,则返回nil + if value == nil || len(value.([]byte)) == 0 { + *a = TextList{} + return nil + } return json.Unmarshal(value.([]byte), a) }