房间与条件的关系

Room relations with conditions

如何给关系添加条件?

例如,我们有对象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;
 }

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

这是道class:

@Dao
public abstract class UserDao { 

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

在您的 DAO 中,您可以指定任何您想要的查询。所以你可以这样做:

@Query("select * from pet_table where userId = :userId and type = :type")
List<Pet> getPetsByUserAndType(int userId, String type)

或者类似的东西,我不确定你的 table 名字是什么。这有意义吗?

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

例如:User有很多Pet。我们将找到所有 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

作为最后一个选项,您可以自己编写所有查询并将它们组合到一个 abstract DAO class:

@Dao
public abstract class UserDao { 

    @Transaction
    @Query("SELECT * FROM `User`")
    abstract List<UserWithPets> getUsers();

    @Transaction
    @Query("SELECT * FROM `Pet` WHERE userId = :userId AND type = :type")
    abstract List<Pet> getPetsByUser(int userId, String type);

    public List<UserWithPets> getUsersWithDogs() {
        List<UserWithPets> users = getUsers();
        for (User user: users) {
            List<Pet> pets = getPetsByUser(user.id, "dog");
            user.pets = pets;
        }
        return users;
    }
}

public class UserWithPets {
   @Embedded
   public User user;
   
   @Ignore
   public List<Pet> pets;
   
   // Other stuff
   // @Relation(parentColumn = "id", entityColumn = "parentId")
   // public List<Child> children;
 }