Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to sort on a foreign key constraint's column count? #1142

Open
daniel-res opened this issue Apr 30, 2024 · 0 comments
Open

How to sort on a foreign key constraint's column count? #1142

daniel-res opened this issue Apr 30, 2024 · 0 comments

Comments

@daniel-res
Copy link

daniel-res commented Apr 30, 2024

Your Question

Hello, I'm not sure on the best approach here, but am looking for some feedback. I want to be able to perform a sort based on the total count of the number of SubGroups associated with the same Group.

I have these two structs:

type SubGroup struct {
	gorm.Model
	
	Name           
	Status          int
}

type Group struct {
	gorm.Model
	
	Author       *string
	Color        string
	Name string
	
	SubGroups []*SubGroup
}

And am currently using the following approach to sorting on Group top-level columns. I have defined a method to dynamically pass in applicable column names, etc. to build up the required query.

var q = queries.Use(pageDb).Group
var builtQuery = q.WithContext(context.Background()).Preload(field.Associations)

var orderQuery = getFieldExpression(orderBy, sortBy)
if orderQuery != nil {
	builtQuery = builtQuery.Order(orderQuery)
}

func getSortedFieldExpression(orderBy, sortBy string) field.Expr {
	var columnField *field.Field = nil
	switch sortBy {
	case "author":
		var c = field.NewField(tableName, "author")
		columnField = &c
	case "color":
		var c = field.NewField(tableName, "color")
		columnField = &c
	case "totalStatuses":
		// ??? todo
	}
	
	if columnField == nil {
		return nil
	}
	
	if orderBy == "desc" {
		return columnField.Desc()
	}
	
	return columnField
}

Any help / suggestions is appreciate, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant