房间与条件的关系

wal*_*mar 7 android relationship android-room

如何为关系添加条件?

例如,我们有对象Pet

    @Entity
     public class Pet {
         @ PrimaryKey
         int id;
         int userId;
         String name;
         String type;
         // other fields
     }
Run Code Online (Sandbox Code Playgroud)

和对象用户

public class User {
     int id;
     // other fields
 }
Run Code Online (Sandbox Code Playgroud)

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

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

如何通过类型获得宠物用户?只有狗或只有猫

这是dao类:

@Dao
public abstract class UserDao { 

   @Query("SELECT * FROM `users`")
   public abstract UserAllPets getUserWithPets();
}
Run Code Online (Sandbox Code Playgroud)

dph*_*ans 5

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

例如:User有很多Pets。我们会找到 all Pet,通过User's id 和Pet's age 大于等于 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()
}
Run Code Online (Sandbox Code Playgroud)

而在你 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>>
}
Run Code Online (Sandbox Code Playgroud)

SQL 语法突出显示:

@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()
}
Run Code Online (Sandbox Code Playgroud)

  • 您是否有想法使“PETS._ID AS PETS__ID,PETS._USER_ID AS PETS__USER_ID”部分更容易?30个参数呢? (2认同)
  • 我试过没有成功`警告:查询返回一些列 [PETS__ID, PETS__USER_ID] 不被 UserPets 使用。您可以在字段上使用 @ColumnInfo 注释来指定映射。您可以通过使用 @SuppressWarnings(RoomWarnings.CURSOR_MISMATCH) 注释方法来抑制此警告。查询返回的列:_ID、PETS__ID、PETS__USER_ID。UserPets 中的字段:_ID。` (2认同)