在 Room 中创建实体之间的关系

Creating Relationships between Entities in Room

我正在尝试在 android 中实现按名称搜索地点。我创建了两个实体,WordPlace

@Parcelize
@Entity
data class Place(
    @PrimaryKey
    val id: String,
    val name: String,
    val icon: String,
    val latitude: Double,
    val longitude: Double,
    val address: String
) : Parcelable
@Entity
data class Word(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    val searchWord: String,
    val placeId: String
)

我还创建了另一个 data class 来模拟 WordPlace 之间的一对多关系。

data class WordWithPlaces(
    @Embedded
    val word: Word,
    @Relation(parentColumn = "placeId", entityColumn = "id")
    val places: List<Place>
)

我遇到的问题是,当我查询数据时,我得到 null

这是dao中的查询函数。

  @Transaction
    @Query("SELECT * FROM Word WHERE searchWord = :searchWord")
    fun getWordsWithPlaces(searchWord: String): LiveData<WordWithPlaces>

我需要帮助才能使实施工作。

我的错误在于架构。

这不是一对多关系,而是多对多关系。我不得不使用两个查询来实现搜索。

    // search for places online based on a searchWord
    // create words consisting of each place's id and the searchWord
    // save the words and places in the database
    suspend fun searchPlaces(searchWord: String) {
        return try {
            val searchResults: PlaceTextSearch = getNetworkService().searchPlaces(searchWord)
            val places = searchResults.places
            val words = places.map { Word(word = searchWord, placeId = it.id) }
            dao.insertWords(words)
            dao.insertPlaces(places)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // get the words matching a searchword
    // get all related places based on those words
    suspend fun getPlaces(searchWord: String): List<Place> {
        val words = dao.getWords(searchWord)
        val placeIds = words.map { it.placeId }.toTypedArray()
        return dao.getPlaces(placeIds)
    }