如何为关系添加条件?
例如,我们有对象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();
}
答案 0 :(得分:2)
只需在您的所有者模型中创建一个包装器,使用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
}
// 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>>
}
答案 1 :(得分:0)
在您的DAO中,您可以指定您想要的任何查询。所以你可以这样做:
@Query("select * from pet_table where userId = :userId and type = :type")
List<Pet> getPetsByUserAndType(int userId, String type)
或类似的东西,我不确定你的桌名是什么。这有意义吗?
答案 2 :(得分:0)
作为最后一个选项,您可以自己编写所有查询并将它们组合在一个抽象 DAO 类中:
@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;
}