【问题标题】:How to get data from @relation where child condition如何从 @relation where child condition 获取数据
【发布时间】:2020-06-20 08:24:37
【问题描述】:

我想使用 @Relation 从一对一的关系中获取数据,但需要为孩子提供条件

@Entity
public class User {
    @PrimaryKey public long userId;
    public String name;
    public int age;
}

@Entity
public class Library {
    @PrimaryKey public long libraryId;
    public long userOwnerId;
    public String code;

}
public class UserAndLibrary {
    @Embedded public User user;
    @Relation(
         parentColumn = "userId",
         entityColumn = "userOwnerId"
    )
    public Library library;
}
@Transaction
@Query("SELECT * FROM User") // I want to get where library.code = "123"
public UserAndLibrary getUsersAndLibraries();

我想要的数据是来自用户的所有数据,其中 library.code = "123" 我知道我可以使用@Embedded,但我的数据使用许多相同的名称,我不想使用前缀。所以我想知道如何使用@Relation 来做到这一点

谢谢

【问题讨论】:

标签: android android-room


【解决方案1】:

使用@Relation,您不能设置“子”条件。 因此,如果您不想处理表的连接,您的选择是替换 UserAndLibrary 中的父/子类:

public class UserAndLibrary {
    @Embedded public Library library;
    @Relation(
         parentColumn = "userOwnerId",
         entityColumn = "userId"
    )
    public User user;
}

和道:

@Transaction
@Query("SELECT * FROM library Where code = :code") // now you can set condition
public UserAndLibrary getUsersAndLibraries(String code);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2016-10-29
    相关资源
    最近更新 更多