从具有多对多关系的房间中查询

时间:2019-12-06 09:50:31

标签: android many-to-many android-room

我的实体之间有很多关系。

@Entity
data class Exercise(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0L
    val name: String = "",
    val description: String = ""
)

@Entity
data class Round(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0L,
    val name: String = "",
    val reps: Int = 0
)

@Entity
data class ExerciseRound(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    val exerciseId: Long = 0,
    val roundId: Long = 0,
    val weight: Int = 0
)

我不知道如何从room类中查询,该类将包含该回合的所有练习以及ExerciseRound表中的字段。像这样:

data class RoundExerciseRelation(
    @Embedded
    val round: Round,        
    val exerciseRelation: List<ExerciseRelation>
)

data class ExerciseRelation (
    val exercise: Exercise
    val roundData: ExerciseRound,
)

2 个答案:

答案 0 :(得分:0)

尝试这些操作,您将获得解决方案

    @Query("SELECT name FROM tb_exercise where id IN ( SELECT roundId FROM tb_round where roundId IN ( SELECT roundId FROM tb_exercise_round where roundId=: roundId ")
    Maybe<List<String>> getExercise(String roundId);
(OR)
    @Query("SELECT * FROM tb_exercise where id IN ( SELECT roundId FROM tb_round where roundId IN ( SELECT roundId FROM tb_exercise_round where roundId=: roundId ")
    Maybe<List<Exercise>> getExercise(String roundId); 

答案 1 :(得分:0)

这是在会议室中定义一对多关系的方式

class RoundExerciseRelation {
    @Embedded
    val round: Round,

    @Relation(parentColumn = "id", entityColumn = "package_id", entity = ExerciseRelation::class)
    val exerciseRelation: List<ExerciseRelation>

}

对于很多人来说,我们需要创建一个单独的表来存储关系并使用联接查询