How to store what user have searched and its resul

2019-08-17 01:46发布

问题:

I want to create a database to store what user have searched, I already have this one :

@Entity(tableName = "user_searched")
data class UserSearched (
    @PrimaryKey
    @NonNull
    @ColumnInfo(name = "item")
    val item: String
)

And then I want to link to it the response, it could be a single item or a list of :

@Entity(tableName = "my_item")
data class MyItem(
    @PrimaryKey
    @NonNull
    @ColumnInfo(name = "id")
    val id: Int,
    @ColumnInfo(name = "name") val name: String,
    @ColumnInfo(name = "description") val description: String
)

But then I don't know how to create the relation, I mean I want to do a query for instance, if the item "android" has searched before, just return the list of MyItem as an answer.

How can achieve it with Room db? I'm using rxJava.

IMPORTANT NOTE

There's a possibility when user search "Android" it contains a list of devices on this case List<MyItem> ok, the thing is if user search for "Google" it can show also items shown with "Android" so, I don't know if a good idea is create like a ForeignKey for MyItem because it can contains more than one...

EDIT

Just created a Join table to link them as follows :

@Entity(
    tableName = "name_item_join", primaryKeys = ["name", "item_id"], foreignKeys = [
        ForeignKey(
            entity = MySearch::class,
            parentColumns = ["name"],
            childColumns = ["join_name_id"]
        ),
        ForeignKey(
            entity = MyItem::class,
            parentColumns = ["item_id"],
            childColumns = ["join_item_id"]
        )
    ]
)
data class NameItemJoin(
    @ColumnInfo(name = "join_name_id")
    val nameId: Int,
    @ColumnInfo(name = "join_item_id")
    val itemId: Int
)

So now, my question is, whenever I add a record into UserSearched and then inside MyItem do I have to manually add them into NameItemJoin? Also do I have to create a @Dao to get all of the items given by name, right?

Flow is : First insert to UserSearched Second insert to MyItem Then I'd like to fill the NameItemJoin so whenever I search for an item_id I get the List or anything.