Ent: user-group M-M and O-M

Created on 16 Oct 2020  路  3Comments  路  Source: ent/ent

I run this example (https://entgo.io/docs/schema-edges/#o2m-two-types)[https://entgo.io/docs/schema-edges/#o2m-two-types]

and I have one more relationship to added:

  • one user can create many groups
  • one group can only belongs to one user.

I tried to add this code but get error:

// user.go 
// Edges of the User.
func (User) Edges() []ent.Edge {
    return []ent.Edge{
                // m2m
        edge.From("groups", Group.Type).
            Ref("users"),
                // o2m
        edge.To("groups", Group.Type),
    }
}

// group.go 
// Edges of the Group.
func (Group) Edges() []ent.Edge {
    return []ent.Edge{
             // m2m
            edge.To("users", User.Type),
                 // o2m
        edge.From("owner", User.Type).
            Ref("groups").
            Unique(),
    }
}

then I run go generate . and run migrate. get error:

../ent/user/user.go:37:2: EdgeGroups redeclared in this block
    previous declaration at ../ent/user/user.go:35:15
../ent/user/user.go:47:2: GroupsTable redeclared in this block
    previous declaration at ../ent/user/user.go:42:16
../ent/user/user.go:50:2: GroupsInverseTable redeclared in this block
    previous declaration at ../ent/user/user.go:45:23
../ent/user/where.go:1054:6: HasGroups redeclared in this block
    previous declaration at ../ent/user/where.go:1026:18
../ent/user/where.go:1055:24: HasGroups.func1 redeclared in this block
    previous declaration at ../ent/user/where.go:1027:24
../ent/user/where.go:1066:6: HasGroupsWith redeclared in this block
    previous declaration at ../ent/user/where.go:1038:46
../ent/user/where.go:1067:24: HasGroupsWith.func1 redeclared in this block
    previous declaration at ../ent/user/where.go:1039:24
../ent/user/where.go:1073:38: HasGroupsWith.func1.1 redeclared in this block
    previous declaration at ../ent/user/where.go:1045:38

Question

All 3 comments

You can't have two edges with the same name (i.e groups in User.Edges).

Hey @clearcodecn,
You can give them different names as follows:

// user.go 
// Edges of the User.
func (User) Edges() []ent.Edge {
    return []ent.Edge{
        edge.From("groups", Group.Type).
            Ref("users"),
        edge.To("managed_groups", Group.Type),
    }
}
func (Group) Edges() []ent.Edge {
    return []ent.Edge{
            edge.To("users", User.Type),
        edge.From("owner", User.Type).
            Ref("managed_groups").
            Unique(),
    }
}

I'll add a check for it the codegen to provide more meaningful error.

@a8m Thanks for your help
馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ernado picture ernado  路  5Comments

ernado picture ernado  路  3Comments

dilipkk-foyernet picture dilipkk-foyernet  路  4Comments

rotemtam picture rotemtam  路  4Comments

ernado picture ernado  路  4Comments