使用Android房间关系搜索查询

使用Android房间关系搜索查询

本文介绍了使用Android房间关系搜索查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android房间关系中,可以使用相关表的属性来使用搜索查询.下面是我的表结构.在此,我将交易与付款和行(交易项目)相关联.我在用户界面中有一个搜索字段,用户可以在其中使用付款表中的付款金额进行搜索.如何形成查询以访问付款表的属性.

In Android room relation, is it possible to use search query using the property of the related table. Below is my table structure. In this i am relating transaction with payment and lines(transaction items). I have an search field in my UI where the user could search using payment amount which is inside payment table. How to form a query to access the properties of payment table.

class TransactionWithPaymentAndLines(
    @Embedded
    var transactions: Transactions? = null,

    @Relation(
        parentColumn = "id",
        entityColumn = "transactionId",
        entity = Payment::class
    )
    var payments: List<Payment> = listOf(),

    @Relation(
        parentColumn = "id",
        entityColumn = "transactionId",
        entity = TransactionLines::class
    )
    var transactionLines: List<TransactionLines> = listOf()
)

推荐答案

理想的方法是查询多个相关表是创建视图.视图使用 join 组合来自两个或多个表的数据.

Ideal way is to query multiple related tables is to create a View. A view combines data from two or more tables using join.

在Android中,使用房间持久性库,您可以创建这样的视图,然后您可以查询视图字段.这是您可以做到的方式:

In Android, using Room Persistance library, you can create such a view, and then you can query the fields of view. This is how you can do it:

假设您有表格:

用户:ID,名称,部门ID

User: id, name, departmentId

部门:ID,姓名

创建视图:

@DatabaseView("SELECT user.id, user.name, user.departmentId," +
        "department.name AS departmentName FROM user " +
        "INNER JOIN department ON user.departmentId = department.id")
data class UserDetail(
    val id: Long,
    val name: String?,
    val departmentId: Long,
    val departmentName: String?
)

将视图添加到数据库:

@Database(entities = arrayOf(User::class),
          views = arrayOf(UserDetail::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDetailDao(): UserDetailDao
}

创建DAO:

@Dao
interface UserDetailDao {
    @Query("SELECT * FROM UserDetail")
    fun loadAllUserDetails(): Array<UserDetail>
}

现在,您可以使用此DAO查询视图.

Now, you can query a View using this DAO.

这篇关于使用Android房间关系搜索查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:57