rrubick
V2EX  ›  Android

请教个 android room 查询问题

  •  
  •   rrubick · Feb 17, 2025 · 3953 views
    This topic created in 514 days ago, the information mentioned may be changed or developed.
    data class AreaAndMedia(
        @Embedded
        val area: Area,
        @Relation(parentColumn = "objId" , entityColumn = "bindArea")
        var medias: List<Media>
    )
    
    data class Media(
    	@ColumnInfo(name = "taskId", defaultValue = "")
        val taskId: String = ""
    )
    
    interface Dao {
    	@Transaction
        @Query("select * from area where objId = :areaId")
        fun selectAreaAndMediasById(areaId: String): 	Flow<List<AreaAndMedia>>
    }
    

    现在,我想新增一个查询方法,用意是过滤 Media ,例如

    @Transaction
        @Query(
            "SELECT af.* FROM area af WHERE af.objId = :areaId AND EXISTS ( SELECT 1 FROM medias mi WHERE mi.bindArea = af.objId AND mi.taskId = '')"
        )
        fun selectAreaAndMediasWithEmptyTaskId(
            areaId: String
        ): Flow<List<AreaAndMedia>>
    

    但是这个结果中,仍然包含 taskId 不为空的 Media, 不知道问题出在哪里

    3 replies    2025-02-18 09:30:38 +08:00
    linhua
        1
    linhua  
       Feb 17, 2025
    你的问题在于 @Relation 注解的使用方式。 @Relation 注解会自动加载所有与 parentColumn 匹配的 entityColumn 的记录,而不会考虑你在 @Query 中对 Media 表的过滤条件。因此,即使你在 @Query 中使用了 EXISTS 子句来过滤 Media ,@Relation 仍然会加载所有关联的 Media 对象。

    https://stackoverflow.com/questions/49005681/room-relations-with-conditions
    rrubick
        2
    rrubick  
    OP
       Feb 17, 2025
    @linhua #1
    感谢,我研究研究。
    第三方库把好多实现都隐藏,有问题不好去排查。倒不如我直接写 sql 了
    rrubick
        3
    rrubick  
    OP
       Feb 18, 2025
    @linhua #1
    Area 也是 data class, 无法像链接里一样去继承
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   980 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 22:16 · PVG 06:16 · LAX 15:16 · JFK 18:16
    ♥ Do have faith in what you're doing.