zoukankan      html  css  js  c++  java
  • [Go] 在gin框架gorm下查询一对多的数据

    go-fly客服系统快捷回复功能 , 需要获取到分组名以及分组名下的回复内容

    数据库的表结构是 , group_id是关联字段 , user_id是用户id:

    CREATE TABLE `reply_group` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `group_name` varchar(50) NOT NULL DEFAULT '',
     `user_id` varchar(50) NOT NULL DEFAULT '',
     PRIMARY KEY (`id`),
     KEY `user_id` (`user_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    
    CREATE TABLE `reply_item` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `content` varchar(1024) NOT NULL DEFAULT '',
     `group_id` int(11) NOT NULL DEFAULT '0',
     `user_id` varchar(50) NOT NULL DEFAULT '',
     `item_name` varchar(50) NOT NULL DEFAULT '',
     PRIMARY KEY (`id`),
     KEY `user_id` (`user_id`),
     KEY `group_id` (`group_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8

    可以使用下面这种形式变通实现 , 查询两条sql语句 , 程序中对返回的结果进行合并处理

    为了不进行嵌套循环 , 使用空间换时间的方式增加了map[string]*ReplyGroup  映射  , 再利用指针的原理 , 直接往结构体成员上增加元素

    models下的代码

    package models
    
    type ReplyItem struct {
        Id       string `json:"item_id"`
        Content  string `json:"item_content"`
        GroupId  string `json:"group_id"`
        ItemName string `json:"item_name"`
        UserId   string `json:"user_id"`
    }
    type ReplyGroup struct {
        Id        string       `json:"group_id"`
        GroupName string       `json:"group_name"`
        UserId    string       `json:"user_id"`
        Items     []*ReplyItem `json:"items";"`
    }
    
    func FindReplyByUserId(userId interface{}) []*ReplyGroup {
        var replyGroups []*ReplyGroup
        //DB.Raw("select a.*,b.* from reply_group a left join reply_item b on a.id=b.group_id where a.user_id=? ", userId).Scan(&replyGroups)
        var replyItems []*ReplyItem
        DB.Where("user_id = ?", userId).Find(&replyGroups)
        DB.Where("user_id = ?", userId).Find(&replyItems)
        temp := make(map[string]*ReplyGroup)
        for _, replyGroup := range replyGroups {
            replyGroup.Items = make([]*ReplyItem, 0)
            temp[replyGroup.Id] = replyGroup
        }
        for _, replyItem := range replyItems {
            temp[replyItem.GroupId].Items = append(temp[replyItem.GroupId].Items, replyItem)
        }
        return replyGroups
    }

     返回的结果就是上面截图这种形式了.

  • 相关阅读:
    bash 中有效建立锁
    go 语言 Makefile 指定依赖包位置
    在 mysql 中对特定的库禁用 DDL 语句
    go 语言并发机制 goroutine 初探
    Google和facebook如何应用R进行数据挖掘
    数据应用催生商业模式
    4款语音播报来电短信应用[Android]
    让 php 用 nginx 打包 zip
    10个关于 Dropbox 的另类功用(知乎问答精编)[还是转来了]
    分析以数据挖掘技术预测用户流失情况的方法
  • 原文地址:https://www.cnblogs.com/taoshihan/p/14140393.html
Copyright © 2011-2022 走看看