【问题标题】:android room relation: columns are missingandroid房间关系:缺少列
【发布时间】:2021-10-23 10:26:38
【问题描述】:

我在定义两个实体之间的关系时遇到问题。关系是一对一的。每个设备都分配到一个房间。

设备实体:

@Entity
data class Device(
@PrimaryKey(autoGenerate = false) val ipAddress: String,
    val deviceName: String,
    val type: Int,
    val uniqueRoomId: Int
) {
    @Ignore
    val status: DeviceStatus = DeviceStatus.Off
}

房间实体

@Entity
data class Room(
    @PrimaryKey(autoGenerate = true) val roomId: Int,
    val name: String
)

设备和房间对象:

data class DeviceAndRoom(
    @Embedded val room: Room,

    @Relation(
        parentColumn = "roomId",
        entityColumn = "uniqueRoomId",
        entity = Device::class
    )
    val device: Device
)

DeviceDao:

@Dao
interface DeviceDao {
    @Transaction
    @Query("SELECT * FROM Device")
    fun getAllDeviceAndRooms(): LiveData<List<DeviceAndRoom>>

    [...]
}

但我收到以下构建错误:

The columns returned by the query does not have the fields [roomId,name] in com.test.mytestapp.models.DeviceAndRoom even though they are annotated as non-null or primitive. Columns returned by the query: [ipAddress,deviceName,type,uniqueRoomId]

我关注了official android guidelines,但还有其他文章描述了相同的过程,例如Database relations with Room

我不知道出了什么问题。也许有人有想法。

【问题讨论】:

    标签: android sql database kotlin android-room


    【解决方案1】:

    对于该关系(房间(嵌入)与设备(关系)),您可以查询父级:-

    @Query("SELECT * FROM room")
    fun getAllDeviceAndRooms(): LiveData<List<DeviceAndRoom>>
    
    • 名字应该是 RoomAndDevice

    即它无法在设备表中找到 roomid 和 name 列,因为它们在房间表中。然后通过底层查询从每个检索到的房间中检索设备,按照SELECT * FROM the_relationship_entity WHERE entityColumn = parentColumn 的行,因此建议使用@Trasnaction

    如果您想要设备及其房间,那么您可以使用:-

    data class DeviceAndRoom(
        @Embedded val device: Device,
    
        @Relation(
            entityColumn = "roomId",
            parentColumn = "uniqueRoomId",
            entity = Room::class
        )
        val room: Room
    )
    

    还有:-

    @Transaction
    @Query("SELECT * FROM Device")
    fun getAllDeviceAndRooms(): LiveData<List<DeviceAndRoom>>
    

    【讨论】:

    • 非常感谢您的建议!奇迹般有效。我完全忽略了我的 sql 查询中的表名。你建议的代码就是我要找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 2020-10-03
    • 2020-02-01
    • 1970-01-01
    相关资源
    最近更新 更多