pg icon indicating copy to clipboard operation
pg copied to clipboard

Recursively retrieve relations of the model?

Open latipovsharif opened this issue 4 years ago • 3 comments

Is there any way to get relations recursively? for example I've got the following struct:

type Tree struct {
	ID          int
	Parent   *Tree
	ParentID string
	Name     string
}

and I need to get all children of the object recursively. For now I'm doing like this

trees := []Tree{}
db.Model(&trees).Relation("Parent").Relation("Parent.Parent").Where("parent_id is null").Select()

it works if there is only two levels of depth but what if I don't know the depth of the relation?

latipovsharif avatar Jul 07 '19 10:07 latipovsharif

@latipovsharif edit to write beauty code please.

frederikhors avatar Jul 12 '19 18:07 frederikhors

@frederikhors please look at this.

latipovsharif avatar Jul 14 '19 13:07 latipovsharif

Try to google "postgres tree" if you need a tree. I don't think you should be using ORM to build it.

vmihailenco avatar Jul 15 '19 07:07 vmihailenco