简体   繁体   中英

update multiple tables in Android Room Database

I have two models

Types Model

@Entity(tablename="tbl_types")
data class Types(
@PrimaryKey(autoGenerate = true)
    val typesId:Int,
    val name: String?,
    val posts:List<Post>?))

PostModel

@Entity(tablename="tbl_post")
data class Post(
@PrimaryKey(autoGenerate = true)
    val postId:Int,
    val name: String?,
    val details:String?))

A post can be a part of different types so when I change the post's data like name or details I want to update all the types that have this specific post in its posts column. How do I do that?. Do I have to update the type table manually? I don't quite know how the foreign key works and if it will let me update the item on the list or not.

Ok Room support Embedded objects in an entity so lets make Post embedded in Type like this:

@Entity(tablename="tbl_types")
data class Types(
@PrimaryKey(autoGenerate = true)
    val typesId:Int,
    val name: String?,
    @Embedded val posts:List<Post>?))

now for updating the post you easily just change the desired post in the list, in the Type Model and you just need to say:

@Update
fun updateType(type: Types)

and that's the power of Room for updating a row easily. Hope it Helps.

Not containing Post in Type table. Create third table to save the relateion of post and type.

@Entity(tablename="tbl_types")
data class Types(
@PrimaryKey(autoGenerate = true)
    val typesId:Int,
    val name: String?)

@Entity(tablename="tbl_post")
data class Post(
@PrimaryKey(autoGenerate = true)
    val postId:Int,
    val name: String?,
    val details:String?))

@Entity(tablename="type_post_relation", primaryKeys =
    ["postId","typeId"])
data class PostTypeRelation(
    val postId:Int,
    val typeId: Int,
)

...
@Query("UPDATE Tour SET typeId = :toTypeId WHERE postId = :postId and typeId = : fromTypeId")
fun updatePostType(postId: Int, fromTypeId: Int, toTypeId: Int)

The relation table uses postId and typeId to be primary key. When changing post type, just update relation table with a postId and typeId. And if you want to query all posts in one specific type, you can use sql to combine query, so querying post's types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM