Related queries in gorm

Blocker, come one, go one.

Conquer related queries.

Today I asked the company's front end and checked the gitlab API specifications.

It proved that the idea of ​​last night was too naive, and it was more formal to do it once in relational query.

So, find the relevant CASE to achieve.

https://segmentfault.com/a/1190000019331511

https://www.jianshu.com/p/b2de317bfe4a

I use Preload. The implementation idea is as follows (due to the use of encapsulation, so it is more tortuous):

One, what the database looks like

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 with foreign keys

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"`
}

  

Second, read the repository.go of the data model

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
}

  

Three, finally call the basic 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
}

  

Fourth, the data transmitted to the front end

Fifth, what the front end looks like

Guess you like

Origin www.cnblogs.com/aguncn/p/12701450.html