gpt4 book ai didi

android - 房间与条件的关系

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:25 24 4
gpt4 key购买 nike

如何给关系添加条件?

例如,我们有对象Pet

    @Entity
public class Pet {
@ PrimaryKey
int id;
int userId;
String name;
String type;
// other fields
}

和对象用户

public class User {
int id;
// other fields
}

为了让用户拥有宠物,我们制作对象

public class UserAllPets {
@Embedded
public User user;
@Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
public List<PetNameAndId> pets;
}

如何按类型获取宠物用户?只有狗或只有猫

这是dao类:

@Dao
public abstract class UserDao {

@Query("SELECT * FROM `users`")
public abstract UserAllPets getUserWithPets();
}

最佳答案

只需使用 Embedded 从您的所有者模型创建一个包装器,并在您的 DAO 对象中查询 JOIN

例如:用户有很多宠物。我们将找到所有 Pet,按 User 的 id 和 Pet 的年龄大于 9 进行过滤:

@Entity(tableName = "USERS")
class User {
var _ID: Long? = null
}

@Entity(tableName = "PETS")
class Pet {
var _ID: Long? = null
var _USER_ID: Long? = null
var AGE: Int = 0
}

// Merged class extend from `User`
class UserPets : User {
@Embedded(prefix = "PETS_")
var pets: List<Pet> = emptyList()
}

在你的 UserDao

@Dao
interface UserDao {
@Query("""
SELECT USERS.*,
PETS._ID AS PETS__ID,
PETS._USER_ID AS PETS__USER_ID
FROM USERS
JOIN PETS ON PETS._USER_ID = USERS._ID
WHERE PETS.AGE >= 9 GROUP BY USERS._ID
""")
fun getUserPets(): LiveData<List<UserPets>>
}

突出显示的 SQL 语法:

SELECT USERS.*, 
PETS._ID AS PETS__ID,
PETS._USER_ID AS PETS__USER_ID
FROM USERS
JOIN PETS ON PETS._USER_ID = USERS._ID
WHERE PETS.AGE >= 9 GROUP BY USERS._ID

关于android - 房间与条件的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49005681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com