[英]How to add room auto generated Primary key to another entity as a foreign key
@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
)
在這里,我沒有任何常見的字段,所以我如何將這兩個表相關聯,或者如何將房間自動生成的 id 添加為外鍵
一個用@Insert 注釋的方法可以返回一個長的。 這是為插入的行新生成的 ID。 用@Update 注釋的方法可以返回一個int。 這是更新的行數。
update 將嘗試使用 where 子句中的主鍵值更新所有字段。 如果您的實體尚未保存在數據庫中,則更新查詢將無法找到行並且不會更新任何內容。
您可以使用@Insert(onConflict = OnConflictStrategy.REPLACE)。 這將嘗試插入實體,如果存在具有相同 ID 值的現有行,它將刪除它並將其替換為您嘗試插入的實體。 請注意,如果您使用自動生成的 ID,這意味着生成的行將具有與被替換的原始行不同的 ID。 如果您想保留 ID,那么您必須想出一種自定義方法來做到這一點。
所以基本上你有最近插入的項目的主鍵。 您可以在第二個表中插入行時使用該鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.