How to add room auto generated Primary key to another entity as a foreign key

Viewed 300
@Entity 
data class Product (
@PrimaryKey(autoGenerate = true)
var id: Long? = null
)


data class ProductList (
   @Embedded var products: Product,
   @Relation(
            parentColumn = "id",
            entityColumn = "productId",
            entity = GroceryItem::class
    )
    var courses: List<GroceryItem?>? = null
  )


  @Entity
  data class GroceryItem (
     @PrimaryKey
     var id: Int? = null,
     var image: String? = null,
     var price: String?= null
     )

Here I don't have any field as common so how can I relate this two table or how can I add room autogenerated id as a foreign key

1 Answers

A method, annotated with @Insert can return a long. This is the newly generated ID for the inserted row. A method, annotated with @Update can return an int. This is the number of updated rows.

update will try to update all your fields using the value of the primary key in a where clause. If your entity is not persisted in the database yet, the update query will not be able to find a row and will not update anything.

You can use @Insert(onConflict = OnConflictStrategy.REPLACE). This will try to insert the entity and, if there is an existing row that has the same ID value, it will delete it and replace it with the entity you are trying to insert. Be aware that, if you are using auto generated IDs, this means that the the resulting row will have a different ID than the original that was replaced. If you want to preserve the ID, then you have to come up with a custom way to do it.

So basically you have the primary key for the recently inserted Item. You can use that key while inserting row in the 2nd table.

Related