ent / ent/ent

how to recursive query items?

Open
#4,418 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
17.2k
Forks
1k
PR merge metrics
No merged PRs in 30d

Description

i have items with children, the parent and children are M2M same types, as below:

```
func (Item) Fields() []ent.Field {
return []ent.Field{
field.String("code").
NotEmpty().
StructTag(`validate:"required,max=128"`),
field.String("name").
NotEmpty().
StructTag(`validate:"required,max=128"`),
field.Int("level").
Default(1).
StructTag(`validate:"required,gte=0"`),
field.String("parent_id").
Optional(),
}
}

func (Item) Edges() []ent.Edge {
return []ent.Edge{
edge.To("children", Item.Type).
From("parent").
Unique().
Field("parent_id"),
}
}
```

i try a query by:

```
func itemQuery(q *ent.ItemQuery) {
ctx := context.Background()
count, err := q.QueryChildren().Count(ctx)

if count > 0 {
q.WithChildren(itemQuery)
}
}

...

WithItems(itemQuery)
```

but it cannot work, so how to query items with all theire children? untill the leaf node?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.