You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Room(Kotlin)中列车、时刻表、车站表关联查询问题

解决方案

要实现每个经停站的时刻表关联对应车站的完整信息,需要通过嵌套关联的方式,先将ScheduleTable与StationTable绑定,再让TrainTable关联这个组合对象。具体步骤如下:

1. 定义Schedule与Station的关联类

创建一个包含时刻表和对应车站信息的数据类,用@Embedded嵌入ScheduleTable,再通过@Relation关联StationTable:

data class ScheduleWithStation(
    @Embedded val schedule: ScheduleTable = ScheduleTable(),
    @Relation(
        parentColumn = "stationCode",
        entityColumn = "stationCode"
    )
    val station: StationTable = StationTable()
)

2. 修改Train的关联数据类

将原来的List<ScheduleTable>替换为List<ScheduleWithStation>,让列车信息关联包含车站数据的时刻表列表:

data class TrainWithScheduleAndStations(
    @Embedded val train: TrainTable = TrainTable(),
    @Relation(
        parentColumn = "number",
        entityColumn = "trainNumber"
    )
    val schedules: List<ScheduleWithStation> = emptyList(),
    @Relation(
        parentColumn = "sourceCode",
        entityColumn = "stationCode"
    )
    val fromStation: StationTable = StationTable(),
    @Relation(
        parentColumn = "destinationCode",
        entityColumn = "stationCode"
    )
    val toStation: StationTable = StationTable()
)

3. DAO层查询方法

确保查询方法添加@Transaction注解(Room需要事务处理多表关联查询),并返回修改后的关联数据类:

@Dao
interface TrainDao {
    @Transaction
    @Query("SELECT * FROM TrainList WHERE number = :trainNumber")
    suspend fun getTrainWithAllInfo(trainNumber: String): TrainWithScheduleAndStations?
}

原写法问题说明

你之前的关联仅在TrainTable与StationTable之间建立了始发/终到站的关联,但ScheduleTable和StationTable之间没有绑定关系。Room无法自动将每个时刻表的stationCode映射到对应的车站数据,因此只能拿到时刻表自身的字段。通过嵌套ScheduleWithStation,明确了每个时刻表对应的车站关联规则,最终就能获取到包含完整车站信息的经停站列表。

内容的提问来源于stack exchange,提问作者Pawandeep Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 00:12:37