“多对多”选择房间

时间:2019-06-07 10:04:12

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

假设我具有以下实体:

实体A

@Entity(
    tableName = "a_table"
)
data class A(
    val name: String
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "a_id")
    var id: Long = 0
}

实体B

@Entity(
    tableName = "b_table"
)
data class B(
    val type: String
) {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "b_id")
    var id: Long = 0
}

实体B用不同的类型填充。 A个实体可以引用B个实体(“ M:N”关系)。 因此添加了连接实体:

@Entity(
    tableName = "a_b_join",
    primaryKeys = ["fk_a_id", "fk_b_id"],
    foreignKeys = [
        ForeignKey(
            childColumns = arrayOf("fk_a_id"),
            entity = A::class,
            parentColumns = arrayOf("a_id")
        ), ForeignKey(
            childColumns = arrayOf("fk_b_id"),
            entity = B::class,
            parentColumns = arrayOf("b_id")
        )
    ]
)
class ABJoin(
    @ColumnInfo(name = "fk_a_id") var fkAId: Long = 0,
    @ColumnInfo(name = "fk_b_id") var fkBId: Long = 0
)

最后,我想要一个看起来像这样的POJO:

class AwithBPojo {
    @Embedded
    lateinit var a : A

    @???
    val listOfB : List<B> = arrayListOf()
}

为什么这么简单的工作这么难?还是我做错了什么?我只想列出所有A对象和引用的B对象。

我只找到带有以下示例代码的教程:

class AwithBPojo {
    @Embedded
    lateinit var a : A

    @Relation(
        parentColumn = "b_id",
        projection = ["fk_b_id"],
        entityColumn = "fk_b_id",
        entity = ABJoin::class
    )
    val listOfB : List<Long> = arrayListOf()
}

但是我不想只拥有实体B的ID,因为之后合并LiveData很麻烦。

0 个答案:

没有答案