房间数据库。如何从嵌套查询中获取LiveData?

问题描述 投票:0回答:1

我有一个非常简单的数据模型TimeSlot-> Subject-> Teacher。我的目标是每周上学。因此,在SQL中,它将是SELECT * FROM TimeSlot,Subject,WHERE TimeSlot.subject_id = Subject.subject_id和Subject.teacher_id = Teacher.teacher_id。但是我需要一个带有卡片的RecyclerView,其中所有时隙都包含主题和合适的老师。因此,第一部分相当简单=以下数据类:

data class TimeSlotWithSubjects (

    @Embedded val timeSlot: TimeSlot,
    @Relation(
        parentColumn = "subjectId",
        entityColumn = "subject_id"
    )
    val subjects: List<Subject>
)

但是我们在这里没有有关老师的信息。同时我还有另一个数据类:

data class SubjectWithTeacher (

    @Embedded val subject: Subject,
    @Relation(
        parentColumn = "teacher_id",
        entityColumn = "teacherId"
    )
    val teachers: List<Teacher>
)

但是这里我没有有关时隙的信息。请提出一种方法,如何获得包含所有必需信息的LiveData列表?

kotlin android-recyclerview android-livedata data-class
1个回答
0
投票

由于没有好的建议,我通过以下方式解决了任务:

  1. 在ViewModel中:
val teachers_list = db.getAllTeachers()
  1. 在适配器中:
class ViewHolder private constructor (val binding: ListItemTimeSlotWithSubjectAndWeekdayBinding) : RecyclerView.ViewHolder(binding.root){

        companion object {

            lateinit var t_list: List<Teacher>

            fun getTeacherFromList(teacher_id:Long):Teacher?{

                for (teacher in t_list){
                    if (teacher.teacherId == teacher_id)
                        return teacher
                }
                return null
            }

            fun setTeachersList(list: List<Teacher>){
                t_list = list
            }
        }

       fun bind(item: TimeSlotWithSubjects, clickListener: LessonsScheduleListener) {

            //

            if (!item.subjects.isEmpty()){
                binding.subjectName.text = item.subjects[0].name
                //

                if (item.subjects[0].teacherId > 0){

                    val l_teacher = getTeacherFromList(item.subjects[0].teacherId)
                   //

                }

        }
  1. 在片段中:
override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
//
        binding.lessonsScheduleViewModel = viewModel
//
        viewModel.teachers_list.observe(viewLifecycleOwner, Observer {
            it?.let {
                LessonsScheduleAdapter.ViewHolder.setTeachersList(it)
            }
        })
//
    }

我想有更好的方法-请提出建议。至少这一项工作+不违反基本的架构原则]

© www.soinside.com 2019 - 2024. All rights reserved.