ent icon indicating copy to clipboard operation
ent copied to clipboard

Usage Of Edge Schema In Other Edge Types but more indexes.

Open MarshallYang opened this issue 7 months ago • 0 comments

I have two entity, first one is User:

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

// Annotation of the User.
func (User) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.Annotation{Table: "user"},
		entsql.WithComments(true),
	}
}

// Fields of the User.
func (User) Fields() []ent.Field {
	return []ent.Field{
		field.String("nickname").NotEmpty(),
                ...
	}
}

// Edges of the User.
func (User) Edges() []ent.Edge {
	return []ent.Edge{
		edge.To("took_exams", Exam.Type).Through("exam_results", ExamResult.Type),
	}
}

second one is Exam

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

// Annotation of the Exam.
func (Exam) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.Annotation{Table: "exam"},
		entsql.WithComments(true),
	}
}

// Fields of the Exam.
func (Exam) Fields() []ent.Field {
	return []ent.Field{
		field.String("name").NotEmpty(),
	        ...
	}
}

// Edges of the Exam.
func (Exam) Edges() []ent.Edge {
	return []ent.Edge{
		edge.From("exam_users", User.Type).Ref("took_exams").Through("exam_results", ExamResult.Type),
	}
}

User can take exam more then 1 time, so I have a separate table to record user exam histories :

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

// Annotations of the ExamResult.
func (ExamResult) Annotations() []schema.Annotation {
	return []schema.Annotation{
		field.ID("user_id", "exam_id", "times"),
		entsql.Table("exam_result"),
		entsql.WithComments(true),
	}
}

// Fields of the ExamResult.
func (ExamResult) Fields() []ent.Field {
	return []ent.Field{
		field.Int("user_id"),
		field.Int("exam_id"),
		field.Int("times"),
		field.Int("score"),
		...
	}
}

// Edges of the ExamResult.
func (ExamResult) Edges() []ent.Edge {
	return []ent.Edge{
		edge.To("user", User.Type).Field("user_id").Unique().Required(),
		edge.To("exam", Exam.Type).Field("exam_id").Unique().Required(),
	}
}

I want to use user_idexam_id and times to be indexes. but when I run generate error comes out edge schema primary key can only be defined on "id" or ("user_id", "exam_id") in the same order . I don't know what problem I got, or some notices I missed?

MarshallYang avatar Jul 08 '24 15:07 MarshallYang