拦路虎,来一个,去一个。
攻克关联查询。
今天问了公司前端,查了gitlab的API规范,
证明昨晚的想法太天真,关联查询时,还是一次搞定比较正规。
于是,找了相关的CASE来作实现。
https://segmentfault.com/a/1190000019331511
https://www.jianshu.com/p/b2de317bfe4a
我使用的是Preload。实现思路如下(由于使用了封装,所以走得比较曲折):
一,数据库的样子
user.go
type User struct {
gorm.Model
CreatedBy string `json:"created_by"`
UpdatedBy string `json:"updated_by"`
Deleted uint `json:"deteled"`
State uint `json:"state" gorm:"default:1"`
Username string `json:"username"`
Password string `json:"password"`
Avatar string `json:"avatar"`
UserType uint `json:"user_type"`
Application *[]Application
}
project.go
//Project 项目结构体
type Project struct {
gorm.Model
CreatedBy string `json:"created_by"`
UpdatedBy string `json:"updated_by"`
Deleted uint `json:"deteled"`
State uint `json:"state"`
Name string `json:"name"`
CnName string `json:"cn_name"`
Description string `json:"description"`
UserID uint `json:"user_id"`
Application []Application
}
有外键的application.go
type Application struct {
gorm.Model
CreatedBy string `json:"created_by"`
UpdatedBy string `json:"updated_by"`
Deleted uint `json:"deteled"`
State uint `json:"state" gorm:"default:1"`
Name string `json:"name"`
CnName string `json:"cn_name"`
Description string `json:"description"`
Git string `json:"git"`
Jenkins string `json:"jenkins"`
UserID uint `json:"user_id"`
ProjectID uint `json:"project_id"`
User User `gorm:"foreignkey:UserID"`
Project Project `gorm:"foreignkey:ProjectID"`
}
二,读取数据模型的repository.go
func (a *ApplicationRepository) GetApplications(PageNum uint, PageSize uint, total *uint64, where interface{}) *[]models.Application {
var applications []models.Application
other := map[string]string{
"order": " ID desc ",
"foreignkey": " User, Project ",
}
err := a.Base.GetPages(&models.Application{}, &applications, PageNum, PageSize, total, where, other)
if err != nil {
a.Log.Errorf("获取文章信息失败", err)
}
return &applications
}
三,最终调用基本的baseRepository.go
// GetPages 分页返回数据
func (b *BaseRepository) GetPages(model interface{}, out interface{}, pageIndex, pageSize uint, totalCount *uint64, where interface{}, other map[string]string) error {
db := b.Source.DB().Model(model).Where(model).Preload("User").Preload("Project")
if len(other) > 0 {
if _, ok := other["foreignkey"]; ok {
for _, foreignkey := range strings.Split(other["foreignkey"], ",") {
db = db.Preload(strings.TrimSpace(foreignkey))
}
}
if _, ok := other["order"]; ok {
for _, order := range strings.Split(other["order"], ",") {
db = db.Order(strings.TrimSpace(order))
}
}
}
db = db.Where(where)
err := db.Count(totalCount).Error
if err != nil {
b.Log.Errorf("查询总数出错", err)
return err
}
if *totalCount == 0 {
return nil
}
return db.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(out).Error
}
四,传到前端的数据
五,前端解析后的样子
来源:oschina
链接:https://my.oschina.net/u/4382640/blog/3235086