【发布时间】:2019-10-13 18:13:32
【问题描述】:
我在我的 Android 项目中使用 Room 并想编写一个复杂的查询。我搜索了一下,有一些答案女巫说像这样使用 @Embedded:
class TripAndListsAndListItems {
@Embedded
var trip: Trip? = null
@Relation(parentColumn = "creatorId", entityColumn = "remoteId", entity = User::class)
var user: List<User>? = null
@Relation(parentColumn = "remoteId", entityColumn = "tripId", entity = PlanitiList::class)
var lists: List<ListAndListItems>? = null
}
但是我必须在我的代码中弄清楚它以使用循环等来提取我的结果。 我在 @Query 中使用嵌套查询编写了查询,并使用“as”将列与实体字段匹配,如下所示:
这是 ViewModel 类:
class ServiceCard(
val id: Int,
val customerInfo: String,
val time: String,
val oilFilter: Boolean,
val airFilter: Boolean,
val gasFilter: Boolean,
val oil: Boolean
)
并且 @Doa 有一个像这样的 @Query 方法:
@Dao
interface ServiceCardDao :ICommonDao<ServiceCard>{
@Query("SELECT s.services_id as id, " +
"s.user_mobile_no as customerInfo, " +
"( " +
"SELECT count(*) " +
"FROM service_detail as sd " +
"WHERE sd.services_id = s.services_id and sd.service_type_id = 1 " +
") as oilFilter, " +
"( " +
"SELECT count(*) " +
"FROM service_detail as sd " +
"WHERE sd.services_id = s.services_id and sd.service_type_id = 2 " +
") as airFilter, " +
"( " +
"SELECT count(*) " +
"FROM service_detail as sd " +
"WHERE sd.services_id = s.services_id and sd.service_type_id = 3 " +
") as gasFilter, " +
"( " +
"SELECT count(*) " +
"FROM service_detail as sd " +
"WHERE sd.services_id = s.services_id and sd.service_type_id = 4 " +
") as oil, " +
"s.service_date as time " +
"FROM services as s ")
fun selectAllServicesWithDetail(): LiveData<List<model.ServiceCard>>
}
这两者之间有什么优点或缺点吗?
【问题讨论】:
-
对于与 OP 有相同一般问题的任何人,此答案可能会有所帮助:stackoverflow.com/a/62790955/1617737
标签: android android-room android-architecture-components