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

Many-to-many: preload with an order based on an additional column #1248

Open
WinXaito opened this issue Jan 17, 2025 · 0 comments
Open

Many-to-many: preload with an order based on an additional column #1248

WinXaito opened this issue Jan 17, 2025 · 0 comments

Comments

@WinXaito
Copy link

Your Question

Hi guys,

I have a relation many-to-many like that:

Image

type Group struct {
	Uuid              uuid.UUID `gorm:"primaryKey;column:uuid"`
	Name              string    `gorm:"column:name"`

	Machines []*Machine `gorm:"many2many:group_machines;foreignKey:Uuid;joinForeignKey:GroupUuid;References:Uuid;joinReferences:MachineUuid"`
}

type Machine struct {
	Uuid              uuid.UUID `gorm:"primaryKey;column:uuid"`
	Name              string    `gorm:"column:name"`

	Groups []*Group `gorm:"many2many:group_machines;foreignKey:Uuid;joinForeignKey:MachineUuid;References:Uuid;joinReferences:GroupUuid"`
}

// The GroupMachines tables was created automatically, but since I need to keep an order for 
// the machines in a group, I need to have the Rank. So I created a new struct that I included in the migration.
type GroupMachines struct {
	GroupUuid uuid.UUID `gorm:"primaryKey;column:group_uuid"`
	Group *Group
	MachineUuid      uuid.UUID `gorm:"primaryKey;column:machine_uuid"`
	Machine          *Machine
	
	Rank int `gorm:"column:rank"`
}

So, my question is how I can preload a group with the machine, ordered by Rank ?

I tried something like that, but that doesn't work:

gm := query_config.GroupMachines
g := query_config.Group
group, err := g.Where(g.Uuid.Eq(uid)).
	Preload(field.Associations).
	Preload(g.Machines.Order(gm.Rank)).
	First()

With that code, I got the following error: SQL logic error: no such column: group_machines.rank (1)

In fact, I don't necessarily need to have the Rank value, I just need the Machines list in my Group to be ordered correctly.

The document you expected this should be explained

Associations / Preload : indicate how to manage supplementary column in a many-to-many relation.

Expected answer

How to make that work ? :)

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