我的android应用由学期,课程和评估表组成。 “课程”表行具有一个外键来引用“术语”行的主键,而“评估”表行具有外键来引用“课程”行的主键。问题是,有多个可能的“术语和课程”表可供参考,因此我不能仅对每个“评估和术语”行进行硬编码设置外键。事情是外键检查约束迫使一个父表已经与子表的相应外键一起存在,让我创建该新的子实例。如果我尝试以下操作,将无法正常工作:
private static ContentValues getContentValues(Assessment assessment) {
ContentValues values = new ContentValues();
values.put(AssessmentTable.Cols.UUID, assessment.getID().toString());
values.put(AssessmentTable.Cols.TITLE, assessment.getTitle());
values.put(AssessmentTable.Cols.ASSESS_TYPE, assessment.getAssessType());
values.put(AssessmentTable.Cols.DUE_DATE, assessment.getDueDate().getTime());
values.put(AssessmentTable.Cols.GOAL_DATE, assessment.getGoalDate().getTime());
values.put(AssessmentTable.Cols.COL_ASSESS_COURSE_REFERENCE, assessment.getCourseReference()/*this is the foreign key getter I made in my Assessment class*/);
//the getter above doesn't work because the foreign key check constraint fails
return values;
}
当我插入固定数字作为外键时,代码有效
private static ContentValues getContentValues(Assessment assessment) {
ContentValues values = new ContentValues();
values.put(AssessmentTable.Cols.UUID, assessment.getID().toString());
values.put(AssessmentTable.Cols.TITLE, assessment.getTitle());
values.put(AssessmentTable.Cols.ASSESS_TYPE, assessment.getAssessType());
values.put(AssessmentTable.Cols.DUE_DATE, assessment.getDueDate().getTime());
values.put(AssessmentTable.Cols.GOAL_DATE, assessment.getGoalDate().getTime());
values.put(AssessmentTable.Cols.COL_ASSESS_COURSE_REFERENCE, 1);
return values;
}
现在的问题是,我插入的每一行的外键值都为1,因此每个评估都将与主键为1的课程相关。我的应用程序中可以有多门课程,而没有多个评估所有通过主键1或我选择的固定号码链接到同一课程的所有人。
是否没有办法根据我希望与评估相关的课程来动态插入评估的外键?
这是我的评估班,其中包含所有的getter和setter:
public class Assessment {
private UUID mID;
private String mTitle;
private String mAssessType;
private int mCourseReference;
private Date mDueDate;
private Date mGoalDate;
public Assessment() {
this(UUID.randomUUID());
}
public Assessment(UUID id) {
mID = id;
mTitle = new String();
mAssessType = new String();
mDueDate = new Date();
mGoalDate = new Date();
}
public UUID getID() {
return mID;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public String getAssessType() {
return mAssessType;
}
public void setAssessType(String assessType) {
mAssessType = assessType;
}
public Date getDueDate() {
return mDueDate;
}
public void setDueDate(Date dueDate) {
mDueDate = dueDate;
}
public Date getGoalDate() {
return mGoalDate;
}
public void setGoalDate(Date goalDate) {
mGoalDate = goalDate;
}
public int getCourseReference() {
return mCourseReference;
}
public void setCourseReference(int courseReference) {
mCourseReference = courseReference;
}
}
这个想法是使用setCourseReference()设置器来选择将评估链接到所需课程的任何int值,因此,如果我有3个课程,主键分别为1、2和3,则可以使用setCourseReference(int)向评估添加外键,其int取决于用户选择的值为1、2或3。我不能只是预先硬编码一个固定值。课程数不限。