Room relations with conditions
Just create a wrapper from your owner model, using Embedded
and query JOIN
in your DAO object.
For example: User
have many Pet
s. We will find all Pet
, filter by User
's id and Pet
's age greater equal than 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()
}
And in your 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 Syntax highlighted:
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