我有一个 UI 模型CourseUiModel
,我在 ViewModel 中使用它。
data class CourseUiModel(
val Id: String,
val Title: String,
val Subtitle: String,
// Author is missing
val lessonModels: List<LessonUiModel>,
)
data class LessonUiModel(
val Id: String,
val Name: String,
val topicModels: List<TopicUiModel>,
)
data class TopicUiModel(
val Id: String,
val Name: String
)
我在本地数据库上有 3 个表,分别称为Course
、Lesson
和Topic
。实体类是:
@Entity
@Parcelize
data class Course(
@PrimaryKey
val Id: String,
val Title: String,
val Subtitle: String,
val Author: String,
) : Parcelable {}
@Entity(indices = [Index(value = ["CourseId"])],
foreignKeys = [ForeignKey(
entity = Course::class,
parentColumns = arrayOf("Id"),
childColumns = arrayOf("CourseId"),
onDelete = ForeignKey.CASCADE)])
@Parcelize
data class Lesson(
@PrimaryKey
val Id: String,
val Name: String,
val CourseId: String,
val OrderInCourse: Int,
) : Parcelable {}
@Entity(indices = [Index(value = ["LessonId"])],
foreignKeys = [ForeignKey(
entity = Lesson::class,
parentColumns = arrayOf("Id"),
childColumns = arrayOf("LessonId"),
onDelete = ForeignKey.CASCADE)])
@Parcelize
data class Topic(
@PrimaryKey
val Id: String,
val Name: String,
val LessonId: String,
val OrderInLesson: Int,
) : Parcelable {}
如何将我从房间得到的查询映射到这个对象?我目前拥有的是以下内容:
@Query("""SELECT *
FROM Course
JOIN Lesson ON Course.Id = Lesson.CourseId
JOIN Topic ON Lesson.Id = Topic.LessonId
WHERE Course.Id = courseId
ORDER BY Lesson.OrderInCourse, Topic.OrderInLesson ASC""")
fun getCourseModel(courseId: String): LiveData<CourseUiModel>
当我尝试运行它时,我收到以下错误
error: The columns returned by the query does not have the fields [lessonModels] in com.albiders.albiders.ui.Courses.ui_models.CourseUiModel even though they are annotated as non-null or primitive. Columns returned by the query: [Id,Title,Subtitle,Author,Id,Name,CourseId,OrderInCourse,Id,Name,LessonId,OrderInLesson]
该错误是有道理的,但我不知道如何正确执行此操作。