I don't know why edge generate doesn't work in entgo

Viewed 87

i'm trying build app by golang and entgo and falling problem about entgo generate,

https://entgo.io/

below is user table code

type user table

// User holds the schema definition for the User entity.
type User struct {
    ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("nickname").NotEmpty().Unique(),
        field.String("user_type").Default("guest"),
        field.Time("created_at").Default(time.Now()),
        field.Time("updated_at").Default(time.Now()).UpdateDefault(time.Now()),
    }

}

// Edges of the User.
func (User) Edges() []ent.Edge {
    return []ent.Edge{
        edge.To("token", Token.Type),
    }   
}

and below is about token

// Token holds the schema definition for the Token entity.
type Token struct {
    ent.Schema
}

// Fields of the Token.
func (Token) Fields() []ent.Field {
    return []ent.Field{
        field.String("token"),
        field.Int("user_id"),
        field.Time("created_at").Default(time.Now()),
        field.Time("updated_at").Default(time.Now()).UpdateDefault(time.Now()),
    }
}

// Edges of the Token.
func (Token) Edges() []ent.Edge {
    return []ent.Edge{
        edge.From("user", User.Type).Ref("users").Field("user_id"),
    }
}

and im try generate entgo like this

go generate ./ent

but it is not working and i give error like below,

entc/gen: resolve "Token" relations: edge "users" is missing for inverse edge: Token.user(User)
exit status 1

i dont know what

I don't know what's wrong, please help

1 Answers

You've reversed the order of edge.To / edge.From.

See the ent docs:

A schema that defines an edge using the edge.To builder owns the relation, unlike using the edge.From builder that gives only a back-reference for the relation (with a different name).

From your example it looks like you're trying to achieve a O2M relation where a User can have many Tokens associated.

Change the Edges methods on both structs to be:

// Edges of the User.
func (User) Edges() []ent.Edge {
    return []ent.Edge{
        edge.From("token", Token.Type).
            Ref("users"),
    }
}

and

// Edges of the Token.
func (Token) Edges() []ent.Edge {
    return []ent.Edge{
        edge.To("users", User.Type).
            Unique().
            Field("user_id").
            Required(),
    }
}
Related