【问题标题】:Room. error: Multiple fields have the same columnName房间。错误:多个字段具有相同的columnName
【发布时间】:2020-01-09 13:05:37
【问题描述】:

我正在尝试在其中一个表引用另一个表两次的表之间创建关系。代码如下:

@Entity(tableName = "message",
        foreignKeys = [
            ForeignKey(entity = Contact::class,
                    parentColumns = ["id"],
                    childColumns = ["toContactId"],
                    onDelete = NO_ACTION
            ),
            ForeignKey(entity = Contact::class,
                    parentColumns = ["id"],
                    childColumns = ["fromContactId"],
                    onDelete = NO_ACTION)
        ], indices = [Index("toContactId"), Index("fromContactId")]
)
data class Message(
        @PrimaryKey var id: String,
        var creationDate: Date,
        var messageStatus: MessageStatus,
        var toContactId: String,
        var fromContactId: String,
        var text: String
)


@Entity(tableName = "contact")
data class Contact(
        @PrimaryKey val id: String,
        val firstName: String,
        val lastName: String,
        val cellPhone: String,
        val email: String
)

这是我创建“关系”类的方法:

data class MessageRelations(@Embedded var message: Message,
                                @Embedded var toContact: Contact,
                                @Embedded var fromContact: Contact)

这种方法导致 错误:多个字段具有相同的 columnName:id。字段名:message > id, toContact > id, fromContact > id。

我还尝试为注释 @Embedded(prefix = "to_") 和 @Embedded(prefix = "from_") 添加前缀。但在这种情况下,Room 无法在查询返回的文件与 MessageRelations 类中的文件之间找到匹配项。

如果您能提供任何有关如何解决此问题的提示,我将不胜感激。

【问题讨论】:

    标签: android foreign-keys android-room


    【解决方案1】:

    我相信使用 @Relation 而不是 @Embed 将解决这些问题,而不是包含来自实体的字段/变量,它根据关系构建对象。

    所以你会有类似的东西:-

    data class MessageRelations(@Embedded var message: Message,
                                    @Relation(parentColumn = "toContactId", entityColumn = "id") var toContact: Contact,
                                    @Relation(parentColumn = "fromContactId", entityColumn = "id") var fromContact: Contact)
    
    • 请注意,以上是原则性代码,未经测试或运行。

    【讨论】:

    • 在使用@Relation 时,我还应该在Message 实体中指定ForeignKey 吗?
    • @OlehLiskovych 是的(尽管没有必要因为外键主要定义插入/更新/删除的规则,而是使关系发生)。也许看看Which approach should i go for regarding relations in Room DB?
    • 太棒了。只需将“albumId”更改为“id”即可。感谢您的回答和进一步的解释!
    • @OlehLiskovych 哎呀我以为我已经改变了(将相应地编辑答案)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    相关资源
    最近更新 更多