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_id
、exam_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
.
is there sth notices I missed?
I want the exam_record table record user’s everytime exam result.
user_id | exam_id | score |
---|---|---|
1 | 2 | 100 |
1 | 2 | 90 |
how can i achieve this in ent framework.
Marshall Yang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.